﻿using Module_Debug.Hardware;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions; //add 正则变换空间
using System.Threading;
using System.Windows.Forms;
namespace Module_Debug.VDDIC_Gamma
{
    public partial class AGengamma : Form
    {
        //监听ICNA3310挂载
        frmMain frmHelp = null; //for 引用主窗口的comport,IC list 等控件
                                //decale Ca310,410       
        #region  // decale Ca310,410 and comport
        #region //数据类型结构体声明
        struct GammaType //定义IC gamma 信息结构体
        {
            public string ICName;
            public string ProjectName;
            public int GGSectionTuneNum;
            public string GGSectionTree;
            public string[] GGN_SelectSectionlist;
            public string GGN_ClickCode;// for click action code
            public string GGN_StartCode; //for Write 
            public string GGN_EndCode;
            public string EnterGammaMode_Code; //for ryduim IC  Enter measure mode 
            public string ExitGammaMode_Code;
            public string GGN_Target;
            public string GGN_TargetLimit;
            public string GGN_Picname;// for AOD or APL tume gamma pic
            public string GGN_FrameRate; //CA-410 Auto mode framerate
            public int MaxLooptune;
            public string RegType; //long(mulit_par),single,mix   
            public int RegNum; //record  1 color parnum
            public int NodeNum; //IC 寄存器最大node 数
            public int NodeEffetNum; //record 实际调试的 Nodenum 从哪个开始
            public int ParNum; //record  1 color parnum
            public string NodeVector; //0-255 =from 0 to 255;255-0 =from 255  to 0;
            public int Par2LumVector; //+1/ -1 ;1=value relax lum positive,-1=value relax lum negitive
            public int ParBit; //10bit ,8bit record gamma value bit
            public string NodeCorrect; //node 值修正例如nova 不用到的需要与gay255一致
            public string ParBitmap; //MS=H[9:8]+ low[7:0];LS=low[7:0]+H[9:8];Exp 公式决定
            public string NodeMuxPar; //MS=H[9:8]+ low[7:0];LS=low[7:0]+H[9:8];Exp 公式决定
            public string NodePos; //example:NodePos=0,4,16,23,35,60,192,255
            public string MaxNodeValue; //recor verynode max value
            public string[] RGB_PageReg; //Red page switch reg,FE 50
            public string[] RGB_Reg; //Red register adrr B0-C0
                                     //public string Green_PageReg; // page switch reg,,FE 51
                                     //public string Green_Reg; //verynode max value
                                     //public string Blue_PageReg; //  page switch reg,FE 52
                                     //public string Blue_Reg; //verynode max value
            public int[] NodeFollow_A;  //记录node value 重新赋值信息
        }

        struct DBVType //定义IC gamma 信息结构体
        {
            public string Regname;
            public int Valuemax;
            public double Showrate;
            public string Parmap;
            /*
            public int Step;
            public string StartCode;
            public string EndCode;
            */
        }

        struct BtnType //定义按钮结构
        {
            public string Btnname;
            public string BtnCode;
            /*
            public string Btnhotkey; //快捷按键
            public int Top;//for 定义btn 位于容器TOP位置
            public int Left;//for 定义btn 位于容器LEFT位置
            */
        }
        struct NodeTargetType //定义node 对应target 结构体
        {
            public double Lv;
            public double sx;
            public double sy;
            public double sz;
            public double gamma_rate;
            public double UpLv;
            public double LowLv;
            public double Limit_sx;
            public double Limit_sy;
            // public double []XYZ =new double [4] ; 
            public double T;
        }
        struct CASDataType //定义CASDK date 结构体
        {
            public double Lv;
            public double sx;
            public double sy;
            public double sz;
            public double X;
            public double Y;
            public double Z;
            public double T;
            public double duv;
            public double JEITA;
            public double FMA;
            public int R_index;
            public int G_index;
            public int B_index;
            public void SetLvxy(double in_Lv, double in_sx, double in_sy)//带方法的结构体
            {
                this.sx = in_sx;
                this.sy = in_sy;
                this.sz = 1 - in_sy - in_sx;
                this.Lv = in_Lv;
                this.X = in_Lv * in_sx / in_sy;
                this.Y = in_Lv;
                this.Z = in_Lv * (1 - in_sx - in_sy) / in_sy;

            }
        }
        struct ComReciveDataType //定义串口主动回读 date 结构体
        {
            public byte[] buf; //返回buf
            public string bufstr; //返回buf
            public int bufnum; //回读到的buffNum
                               //     public int waitloopnum;//此次回读允许等待最 长时间=waitloopnum*10ms
            public void Initialbuf(int in_num)
            {
                this.bufnum = in_num;
                this.buf = new byte[in_num];
                this.bufstr = "";
            }
            public void Getstring(int in_num)
            {
                bufstr = this.buf[0].ToString("X2");
                for (int i = 1; i < this.bufnum; i++)
                { bufstr += " " + this.buf[i].ToString("X2"); }
            }
        }
        #endregion  // 数据类型结构体声明

        CaSDK CaSDKObj = new CaSDK();

        // CaSDK CaSDKObj = null;
        CMA01 CMadj = new CMA01();
        CRC16 CRCData = new CRC16();
        private bool SendDebugflag = false, RecDebugflag = false, GammaFullDebugflag = false, GammaDebugflag = true, ScriptDebugflag = true;//debug 信息是否显示
        private bool FasteWflag = true;
        private bool Listening = false;//是否没有执行完invoke相关操作
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke
        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过
        private byte[] Send_buf = new byte[1];
        private byte[] Rec_buf = new byte[1];

        private string[] ScriptSavestring = new string[100];
        private string[] ScriptLoadFilestring = new string[100];
        // private string Readbuff = "";
        private List<string> ImageType;
        string GTcfgPath;
        int GTcfgdone = 0;
        string Err_report;// for script 记录Error 信息行数，错误位置
        Bitmap bMap; //存储图
        int GmapH, GmapW;
        public string Picpath = "";
        bool Stopflag = false;      //for auto gamma tune,stop
        bool Lockedflag = false; //for 联动控件加锁防止死锁

        #endregion  // decale parment end

        #region  //decale IC gamma parment
        Label[] LabTitleArry;
        Label[] LabArry;
        NumericUpDown[] NumArry;
        TextBox[,] TextArry;
        Button[] BtnArry;
        RadioButton[] RadioArry;  //=new RadioButton[40];

        Int16[] NodePos_A; //绑点对应灰阶
        Int16[] MaxNodeValue_A; //绑点最大值
        Int16[][] RGB_Value_A = new Int16[3][];//绑点（32个）的RGB 分量值
        Int16[][] RGB_RefValue_A = new Int16[3][];//绑点（32个）的RGB 参考分量值，gamma 时可从此处取值
        string[][] RGB_Reg_A = new string[3][];// RGB 分别 的寄存器[0][]-R,  [1][]-G,  [2][]-B,
        int[][] RGB_Reg_Leght_A = new int[3][];// RGB 分别 寄存器的长度[0][]-R,  [1][]-G,  [2][]-B,
        byte[][] RGB_ParValue_A = new byte[3][]; //RGB 分别寄存器的（64个）参数值

        short[][] RGB_RegIndex_A = new short[3][];// RGB 分别每个绑点（64个）的对应的寄存器,for mix page
        short[][] RGB_ParIndex_A = new short[3][]; //RGB 分别每个绑点（64个）在寄存器的位置是第几个参数 for Mix type
        byte[][] RGB_RegLWrite_A = new byte[40][];// RGB 分别每个绑点（64个）的对应的寄存器,for mix page
        GammaType ICGT; //Ic gamma information include node and reg and  par information
        int offsetx, offsety = 100;
        int Maxarry = 100, MaxarryRecord = 100;

        string HF_GenW_port = "96 20"; //2KS  96端口
        //string InfPath = "";
        DBVType IC51Reg;
        int IC_funBtn_num;
        Button[] Btn_fun_Arry;
        BtnType[] IC_demura = new BtnType[20];
        BtnType[] Function_Btn = new BtnType[200];

        GroupBox[] FGGroupBoxArry = new GroupBox[20];
        RadioButton[] Radio_function = new RadioButton[200];
        #endregion  // decale parment end

        #region//Form load change,close
        public AGengamma(frmMain AGengamma)
        {
            frmHelp = AGengamma;
            InitializeComponent();
            this.tab_script_page.Parent = tab_send_control;
            this.tab_cmd_file.Parent = null;
            frmHelp.Child_window_hide_already = true;
            frmHelp.Child_Gamma_Window_Open_Enable = false;
        }
        public void show_script_cmd(string str)
        {
            this.text_script_send_all.Text = str;
        }
        private void AGengamma_Load(object sender, EventArgs e)
        {
            int tempW, tempH;
            tempW = this.Width;
            tempH = this.Height;
            //groupBox_pattern.Left = tempW - 240;
            //groupBox_CASDK.Left = tempW - 240;
            //groupBox2.Left = tempW - 240;
            tableLayoutPanel1.Left = tempW - 250;
            tabControl1.Width = tempW - 265;
            tabControl1.Height = tempH - 80;
            CAS200_dataGridView.Left = tempW - 275;

            pictureBox2.Width = tempW - 275;
            // CAS200_dataGridView.Left = tempW - 275 - CAS200_dataGridView.Width;
            //pictureBox2.Width = tempW - 275 - CAS200_dataGridView.Width;
            pictureBox2.Height = tempH - 120;
            GmapH = pictureBox2.Height;
            GmapW = pictureBox2.Width;

            MakeArray(400);
            Inital_Paint(GmapW, GmapH);
            CheckdefualtCfg();
            // ShowArray();
            string[] s = { ".bmp" };
            this.ImageType = new List<string>(s);
            Thread.Sleep(5);
            frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
            Thread.Sleep(5);
            frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
            // just test
            //  GTcfgPath = "D:\\002-Code\\1013a\\Debug_App_final\\ICNA3511.gamma";
            //    GetgammCfg(1);// 加载cfg 并默认group1
            //GetgammCfg();
            //   ShowArray();
            CA_Sel.SelectedIndex = 1;
            comBox_Slect.SelectedIndex = 1;
            CaSDK_Measure_Speed.SelectedIndex = 0;
            HF_GenW_port = "96 20";
            /*
            for (int i = 0; i < 10; i++)
            {
                ScriptSavestring[i] = "";
            }
            */
        }

        private void AGengamma_FormClosed(object sender, FormClosedEventArgs e)
        {
            ////frmHelp.comPort.Close()
            frmHelp.comPort.ReceivedBytesThreshold = 1;
            frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
            frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
            ////frmHelp.comPort.Open();
            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Gamma_FormClosed！\r\n";
            frmHelp.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmHelp.Child_window_hide_already = false;
            frmHelp.IC_comboBox.Enabled = true;
        }

        private void AGengamma_SizeChanged(object sender, EventArgs e)
        {
            int tempW, tempH, temp, temtag;
            tempW = this.Width;
            tempH = this.Height;
            if ((tempW > 350) & (tempH > 350))
            {
                tableLayoutPanel1.Left = tempW - 250;
                tabControl1.Width = tempW - 265;
                tabControl1.Height = tempH - 80;
                text_gammaMsg.Top = tempH - 300;
                pictureBox2.Height = tempH - 120;
                CAS200_dataGridView.Height = tempH - 200;
                //tempW = this.Width;
                //tempH = this.Height;
                temtag = Convert.ToInt16(CAS200_dataGridView.Tag);
                if (temtag > 0)//启动过measure gamm 则显示CAS200_dataGridView，不然隐藏
                {
                    CAS200_dataGridView.Visible = true;
                    Btn_CAS200_dataClear.Visible = true;
                    Btn_CAS200_dataSave.Visible = true;
                    checkBox_CAS200_dataHold.Visible = true;
                    //CAS200_dataGridView.Left = tempH - 150;
                    temp = tempW - 275 - CAS200_dataGridView.Width;
                    if (temp > 10)
                    {
                        CAS200_dataGridView.Left = temp;
                        checkBox_CAS200_dataHold.Left = temp + 2;
                        Btn_CAS200_dataClear.Left = temp + 50;
                        Btn_CAS200_dataSave.Left = temp + 125;
                    }
                    temp = tempW - 275 - CAS200_dataGridView.Width;
                    if (temp > 10) pictureBox2.Width = tempW - 275 - CAS200_dataGridView.Width;
                }
                else
                { pictureBox2.Width = tempW - 275; }


                if (GTcfgdone > 0)
                {
                    ShowArray();// 根据布局大小重新显示 按钮
                    GTcfgdone = 2;
                    //  GGourpBox.Left = tempW - 475;
                    //  GGourpBox.Top = tempH - 150 - GGourpBox.Height;
                }
                GmapW = pictureBox2.Width;
                GmapH = pictureBox2.Height;
                //Inital_Paint(formW - 290, formH - 120);
                Inital_Paint(GmapW, GmapH);
                Update_Paint();
                tabControl1.Refresh();
            }
        }
        //select IC gamma inf wenjian

        string Gamma_RGBValueRecordIni = "RGBvaue.txt"; // 全局变量存储调试好gamma 的数据供下次调试调用

        private void ComboBox_Porject_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboxTmp = (ComboBox)sender;
            string defualtinfPath = "";
            string ICPrgname = (comboxTmp).Text;
            string Userpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG";
            if (ICPrgname == "Add New IC")
            {
                OpenFileDialog of = new OpenFileDialog();
                //string strFileName = "";
                of.Filter = @"gamma配置(*.Gamma)|*.Gamma|所有文件(*.*)|*.*"; ;
                of.Title = "Add Gamma Cfg文件";
                if (of.ShowDialog() == DialogResult.OK)
                {
                    GTcfgPath = of.FileName;
                    GetgammCfg(0, "");// 加载cfg 并默认group1
                    ShowGGNBox(GTcfgPath);
                    ShowArray();    // 根据新cfg 文件加载刷新按钮
                    ShowFunctionGroup(); // 根据新cfg 文件加载function按钮
                    string defaultinfPath = Userpath + "\\2K_CFG.inf";
                    bool result = WritePrivateProfileString("Lastlog", "DefualtGammaPath", of.SafeFileName, defaultinfPath);
                    if (File.Exists(Userpath + "\\Gamma_CFG\\" + of.SafeFileName))
                    {
                        if (MessageBox.Show("Gamma 配置库已存在 " + of.SafeFileName + "是否要替换？", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            File.Copy(GTcfgPath, Userpath + "\\Gamma_CFG\\" + of.SafeFileName, true);
                        }
                    }
                    else
                    {
                        File.Copy(GTcfgPath, Userpath + "\\Gamma_CFG\\" + of.SafeFileName, true);
                    }
                }
            }
            else //不是新增就切换加载
            {
                defualtinfPath = Userpath + "\\Gamma_CFGRecord";   //加载script 历史记录到debug 框
                if (!Directory.Exists(defualtinfPath)) //不存在
                { Directory.CreateDirectory(defualtinfPath); }//不存路径在则创建

                if (!Directory.Exists(Userpath + "\\Gamma_CFGRecord" + "\\" + ICPrgname)) //不存在
                { Directory.CreateDirectory(Userpath + "\\Gamma_CFGRecord\\" + ICPrgname); }//不存路径在则创建
                Gamma_RGBValueRecordIni = Userpath + "\\Gamma_CFGRecord\\" + ICPrgname + "\\RGBvalueRecord.ini";
                if (File.Exists(Userpath + "\\Gamma_CFG\\" + ICPrgname))
                {
                    GTcfgPath = Userpath + "\\Gamma_CFG\\" + ICPrgname;
                    GetgammCfg(0, "");// 加载cfg 并默认group1
                    ShowGGNBox(GTcfgPath);
                    ShowArray(); // 根据切换的新cfg 文件加载刷新按钮

                    ShowFunctionGroup(); // 根据新cfg 文件加载function按钮
                    string defaultinfPath = Userpath + "\\2K_CFG.inf";
                    bool result = WritePrivateProfileString("Lastlog", "DefualtProjectName", ICPrgname, defaultinfPath);
                }
            }
            GGourpBox.Text = ICGT.ICName;
            filegamma_init(); //切换新的.gamma文件初始化
        }
        #endregion  // Form load change,close

        #region  //gamma cfg 解析生成加载

        #region  //Ini file Write and read Api decar

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);

        /// 将指定的键值对写到指定的节点，如果已经存在则替换。
        /// <param name="lpAppName">节点，如果不存在此节点，则创建此节点</param>
        /// <param name="lpString">Item键值对，多个用\0分隔,形如key1=value1\0key2=value2
        /// <para>如果为string.Empty，则删除指定节点下的所有内容，保留节点</para>
        /// <para>如果为null，则删除指定节点下的所有内容，并且删除该节点</para>
        /// <param name="lpFileName">INI文件</param>
        /// <returns>是否成功写入</returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

        public string ReadIni(string Section, string Key, string path)
        {
            StringBuilder temp = new StringBuilder(400);
            uint i = GetPrivateProfileString(Section, Key, "", temp, 400, path);
            return temp.ToString();
        }
        public string Readini_BakRead(string First_Section, string Defualt_Section, string Key, string path)// 首先从First read,如果空则从defult 回读
        {
            StringBuilder temp = new StringBuilder(400);
            uint i = GetPrivateProfileString(First_Section, Key, "", temp, 400, path);
            if (i == 0)
            {
                i = GetPrivateProfileString(Defualt_Section, Key, "", temp, 400, path);
            }
            return temp.ToString();
        }

        #endregion  //inf filer write and red
        private void openICGammaCfgToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            //string strFileName = "";
            of.Filter = @"gamma配置(*.Gamma)|*.Gamma|所有文件(*.*)|*.*"; ;
            of.Title = "打开Gamma Cfg文件";

            if (of.ShowDialog() == DialogResult.OK)
            {
                GTcfgPath = of.FileName;
                GetgammCfg(0, "");// 加载cfg 并默认group1
                ShowGGNBox(GTcfgPath);
                ShowArray();  // 根据临时加载的cfg 文件加载刷新按钮

                ShowFunctionGroup(); // 根据新cfg 文件加载function按钮
                //读取文本信息
                //FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
            }
        }

        private void GetgammCfg(int GroupIndex, string inGGSection)
        {
            string temread, GGSection; //GGname =GGN1,GGN2...
            string[] temarry; string[] temarry2;

            //GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName);
            //IC_name = RM692C
            //RegType = single,32,0 - 255,60,1,10,MS
            //NodePos = 0,3,4,8,12,16,20,28,36,44,52,68,84,100,116,132,148,164,180,188,196,204,212,220,228,236,244,248,252,254,255
            //MaxValue = A - 1023
            //Red_pageReg = FE,50;
            //Red_Reg = 00 - 45;
            //Green_pageReg = FE,50;
            //Green_Reg = 48 - 8A;
            //Blue_pageReg = FE,50;
            //Blue_Reg = 8D - D0;
            //F:\SW_project\Dy_com\Dy_com\RM692C.gamma
            //InfPath = "F:\\Sofeware_project\\Dy_com\\Dy_com\\RM692C.gamma";
            // InfPath = "F:\\VisionoX\\0930\\Debug_App\\Module_Debug\\bin\\Debug\\RM692C.Gamma";

            string InfPath = GTcfgPath;
            ICGT.ProjectName = ReadIni("IC_INFO", "Project_Name", InfPath);
            ICGT.ICName = ReadIni("IC_INFO", "IC_name", InfPath);

            temread = ReadIni("IC_INFO", "Version", InfPath);
            temread = temread.Replace("/", "");
            if (Convert.ToInt32(temread.Replace(".", "")) < 4)
            {
                MessageBox.Show("Gamma cfg 配置版本过低，请使用V0.0.4 版本以上配置文件！");
                return;
            }
            // ICGT.GGSectionTuneNum = 1;//初始化设定1
            if (GroupIndex == 0)
            {
                temread = ReadIni("IC_INFO", "GammaGourpNum", InfPath);
                ICGT.GGSectionTree = temread;
                temarry = temread.Split(';');
                if (temarry.Length < 2)
                {
                    //  ICGT.GGSectionTuneNum = Convert.ToInt16(temread);
                }
                else
                {
                    // mark
                    //ICGT.GGSectionTuneNum = Convert.ToInt16(temread);
                }
                GGSection = "GGN0";
                ICGT.EnterGammaMode_Code = ReadIni("GGN0", "EnterGammaMode", InfPath);
                ICGT.ExitGammaMode_Code = ReadIni("GGN0", "ExitGammaMode", InfPath);

                temread = ReadIni("GGN0", "GammaDebugFlag", InfPath);
                if (temread != "") GammaFullDebugflag = true;// gamma debug mode 
                temread = ReadIni("GGN0", "GGN_TargetLimit", InfPath);
                if (temread != "") ICGT.GGN_TargetLimit = temread; //默认加载GGN0的limit设定
                ICGT.MaxLooptune = 60;
                temread = ReadIni("GGN0", "GGN_MaxloopTune", InfPath);
                if (temread != "") ICGT.MaxLooptune = Convert.ToInt32(temread.Replace(";", ""));// 如果有最大值设定则用配置文件里面的；
                GTcfgdone = 1;
                GammaFullDebugflag = false;
            }
            else
            {
                GTcfgdone = 1;
                GGSection = inGGSection;
                // GGSection = "GGN" + GroupIndex.ToString();
            }
            // if ( GroupIndex>=0)
            //{
            ICGT.GGN_ClickCode = ReadIni(GGSection, "GGN_ClickCode", InfPath);
            ICGT.GGN_StartCode = ReadIni(GGSection, "GGN_StartCode", InfPath);
            ICGT.GGN_EndCode = ReadIni(GGSection, "GGN_EndCode", InfPath);
            ICGT.GGN_Target = ReadIni(GGSection, "GGN_Target", InfPath);

            temread = ReadIni(GGSection, "GGN_TargetLimit", InfPath);
            if (temread != "") ICGT.GGN_TargetLimit = temread; //默认加载Section的limit设定


            temread = ReadIni(GGSection, "GGN_MaxloopTune", InfPath);
            if (temread != "") ICGT.MaxLooptune = Convert.ToInt32(temread.Replace(";", ""));// 如果有最大值设定则用配置文件里面的；

            ICGT.GGN_Picname = ReadIni(GGSection, "GGN_Picname", InfPath);
            ICGT.GGN_FrameRate = ReadIni(GGSection, "GGN_FrameRate", InfPath);
            //ICGT.GGN_Picname = temread;// 如果有最大值设定则用配置文件里面的；Readini_BakRead
            string GGN_alone = ReadIni(GGSection, "GGN_Alone", InfPath);
            if (GGN_alone == "1" | GGSection == "GGN0") //=0 follow GGN0, 不然为独立
            {
                temread = ReadIni(GGSection, "RegType", InfPath);
                temarry = temread.Split(',');
                ICGT.RegType = temarry[0].ToUpper();
                // ICGT.NodeEffetNum  = Convert.ToInt16(temarry[1]);// 实际gamma用到的NodeEffect
                ICGT.RegNum = Convert.ToInt16(temarry[1]);
                ICGT.NodeNum = Convert.ToInt16(temarry[2]);
                ICGT.ParNum = Convert.ToInt16(temarry[3]);
                ICGT.NodeVector = temarry[4];
                ICGT.Par2LumVector = Convert.ToInt16(temarry[5]);
                ICGT.ParBit = Convert.ToInt16(temarry[6]);
                ICGT.ParBitmap = temarry[7];
                ICGT.NodeMuxPar = temarry[8];
                ICGT.NodePos = ReadIni(GGSection, "NodePos", InfPath);
                ICGT.MaxNodeValue = ReadIni(GGSection, "MaxNodeValue", InfPath);
                ICGT.NodeCorrect = ReadIni(GGSection, "NodeCorrect", InfPath); //node 矫正
                ICGT.RGB_PageReg = new string[3];
                ICGT.RGB_Reg = new string[3];
                ICGT.RGB_PageReg[0] = ReadIni(GGSection, "Red_PageReg", InfPath);
                ICGT.RGB_Reg[0] = ReadIni(GGSection, "Red_Reg", InfPath);
                ICGT.RGB_PageReg[1] = ReadIni(GGSection, "Green_PageReg", InfPath);
                ICGT.RGB_Reg[1] = ReadIni(GGSection, "Green_Reg", InfPath);
                ICGT.RGB_PageReg[2] = ReadIni(GGSection, "Blue_PageReg", InfPath);
                ICGT.RGB_Reg[2] = ReadIni(GGSection, "Blue_Reg", InfPath);

                ICGT.NodeFollow_A = new int[ICGT.NodeNum];
                RGB_Value_A[0] = new Int16[ICGT.NodeNum]; RGB_Value_A[1] = new Int16[ICGT.NodeNum]; RGB_Value_A[2] = new Int16[ICGT.NodeNum];
                RGB_RefValue_A[0] = new Int16[ICGT.NodeNum]; RGB_RefValue_A[1] = new Int16[ICGT.NodeNum]; RGB_RefValue_A[2] = new Int16[ICGT.NodeNum];
                RGB_ParValue_A[0] = new byte[ICGT.ParNum]; RGB_ParValue_A[1] = new byte[ICGT.ParNum]; RGB_ParValue_A[2] = new byte[ICGT.ParNum];
                RGB_Reg_A[0] = new string[ICGT.RegNum]; RGB_Reg_A[1] = new string[ICGT.RegNum]; RGB_Reg_A[2] = new string[ICGT.RegNum];
                RGB_Reg_Leght_A[0] = new int[ICGT.RegNum]; RGB_Reg_Leght_A[1] = new int[ICGT.RegNum]; RGB_Reg_Leght_A[2] = new int[ICGT.RegNum];


                temarry = ICGT.NodePos.Split(',');
                ICGT.NodeEffetNum = temarry.Length;
                NodePos_A = new Int16[ICGT.NodeEffetNum];//更改为实际输入绑点数量对应灰阶
                for (int i = 0; i < ICGT.NodeEffetNum; i++)
                {
                    NodePos_A[i] = Convert.ToInt16(temarry[i]);
                    RGB_Value_A[0][i] = (Int16)(NodePos_A[i] * 16);
                    RGB_Value_A[1][i] = (Int16)(NodePos_A[i] * 16);
                    RGB_Value_A[2][i] = (Int16)(NodePos_A[i] * 16);
                }
                for (int i = 0; i < ICGT.NodeNum; i++)
                { ICGT.NodeFollow_A[i] = i; }

                if (ICGT.NodeCorrect != "") //node value follow 不是空，有设定，例如nova家不用的设定为255，chipone 后一个256跟随255
                {
                    string[] temLineArry;
                    string[] temIndexArry;
                    int temn0, temn;
                    temLineArry = ICGT.NodeCorrect.Split(';');
                    for (int i = 0; i < temLineArry.Length; i++)
                    {
                        if (temLineArry[i] != "")
                        {
                            temIndexArry = temLineArry[i].Split(',');
                            temn0 = Convert.ToInt32(temIndexArry[0]) - 1;
                            for (int j = 1; j < temIndexArry.Length; j++)
                            {
                                temn = Convert.ToInt32(temIndexArry[j]) - 1;
                                ICGT.NodeFollow_A[temn] = temn0;
                            }
                        }
                    }
                }
                MaxNodeValue_A = new Int16[ICGT.NodeNum]; //绑点 设定最大值
                temarry = ICGT.MaxNodeValue.Split(',');
                temread = ICGT.MaxNodeValue.Substring(0, 1);
                if (temread == "*")//判断是所有一样，还是每个都不同；* 打头相同
                {
                    for (int i = 0; i < ICGT.NodeNum; i++)
                    {
                        MaxNodeValue_A[i] = Convert.ToInt16(temarry[0].Replace("*", ""));
                    }
                }
                else
                {
                    for (int i = 0; i < ICGT.NodeNum; i++)
                    {
                        MaxNodeValue_A[i] = Convert.ToInt16(temarry[i]);
                    }
                }

                if (ICGT.RegType == "SHORT") //for 1Reg+1Par
                {
                    for (int i = 0; i < 3; i++)
                    {
                        temread = ICGT.RGB_Reg[i].Substring(0, 1);
                        if (temread == "^")
                        {
                            temread = ICGT.RGB_Reg[i].Replace("^", "");
                            temread = temread.Replace(";", "");
                            temarry = temread.Split('-');
                            temread = temarry[1];
                            byte sindex = Convert.ToByte(temarry[0], 16);
                            byte eindex = Convert.ToByte(temarry[1], 16);
                            // for (int j = 0; j < eindex - sindex; j++)
                            for (int j = 0; j < ICGT.ParNum; j++)
                            {
                                int a = sindex + j;                                //RGB_Reg_A[i][j] = (byte)a; wait for modify
                            }
                        }
                        else
                        {
                            temarry = ICGT.RGB_Reg[i].Split(';');
                            for (int j = 0; j < ICGT.ParNum; j++)
                            {
                                RGB_Reg_A[i][j] = temarry[j];
                            }
                        }
                    }
                }
                else if (ICGT.RegType == "MIX") //for Reg+PAr1,2,34 eg.ICNA3511
                {
                    string[] readRegindex = new string[3];
                    string[] readParindex = new string[3];
                    short temlong;

                    RGB_RegIndex_A[0] = new short[ICGT.ParNum]; RGB_RegIndex_A[1] = new short[ICGT.ParNum]; RGB_RegIndex_A[2] = new short[ICGT.ParNum];
                    RGB_ParIndex_A[0] = new short[ICGT.ParNum]; RGB_ParIndex_A[1] = new short[ICGT.ParNum]; RGB_ParIndex_A[2] = new short[ICGT.ParNum];
                    readRegindex[0] = ReadIni(GGSection, "Red_RegIndex", InfPath);
                    readParindex[0] = ReadIni(GGSection, "Red_ParIndex", InfPath);
                    readRegindex[1] = ReadIni(GGSection, "Green_RegIndex", InfPath);
                    readParindex[1] = ReadIni(GGSection, "Green_ParIndex", InfPath);
                    readRegindex[2] = ReadIni(GGSection, "Blue_RegIndex", InfPath);
                    readParindex[2] = ReadIni(GGSection, "Blue_ParIndex", InfPath);

                    for (int i = 0; i < 3; i++)
                    {
                        temarry = ICGT.RGB_Reg[i].Split(';');
                        for (int j = 0; j < ICGT.RegNum; j++)
                        {
                            RGB_Reg_A[i][j] = temarry[j];
                            temlong = Convert.ToInt16(temarry[ICGT.RegNum + j], 16);
                            RGB_Reg_Leght_A[i][j] = temlong;
                            RGB_RegLWrite_A[i * ICGT.RegNum + j] = new byte[temlong];
                        }
                        temarry = readRegindex[i].Split(',');
                        temarry2 = readParindex[i].Split(',');
                        for (int j = 0; j < ICGT.ParNum; j++)
                        {
                            RGB_RegIndex_A[i][j] = Convert.ToInt16(Convert.ToByte(temarry[j], 16) - 1);
                            RGB_ParIndex_A[i][j] = Convert.ToInt16(Convert.ToByte(temarry2[j], 16) - 1);
                        }
                    }
                }
                else
                { }
            }
            else if (GGN_alone == "2") //独立设定synapic 
            {
                ICGT.RGB_PageReg[0] = Readini_BakRead(GGSection, "GGN0", "Red_PageReg", InfPath);
                ICGT.RGB_Reg[0] = Readini_BakRead(GGSection, "GGN0", "Red_Reg", InfPath);
                ICGT.RGB_PageReg[1] = Readini_BakRead(GGSection, "GGN0", "Green_PageReg", InfPath);
                ICGT.RGB_Reg[1] = Readini_BakRead(GGSection, "GGN0", "Green_Reg", InfPath);
                ICGT.RGB_PageReg[2] = Readini_BakRead(GGSection, "GGN0", "Blue_PageReg", InfPath);
                ICGT.RGB_Reg[2] = Readini_BakRead(GGSection, "GGN0", "Blue_Reg", InfPath);

                for (int i = 0; i < 3; i++)
                {
                    temarry = ICGT.RGB_Reg[i].Split(';');
                    for (int j = 0; j < ICGT.RegNum; j++)
                    {
                        RGB_Reg_A[i][j] = temarry[j];
                    }
                }
            }
            //   }

            //===DBV 51 reg cfg get===============

            IC51Reg.Regname = ReadIni("DBVREG", "Regname", InfPath);
            TrackBar_51.Maximum = 4095; //默认为4095 ，有设定根据设定更新
            numericUpDown_51Reg.Maximum = 4095;
            temread = ReadIni("DBVREG", "Valuemax", InfPath);
            if (temread.Length > 2)
            {
                IC51Reg.Valuemax = Convert.ToInt32(temread);
                TrackBar_51.Maximum = IC51Reg.Valuemax;
                numericUpDown_51Reg.Maximum = IC51Reg.Valuemax;
            }
            IC51Reg.Parmap = ReadIni("DBVREG", "Parmap", InfPath);
            IC51Reg.Showrate = 1; //默认为1 ，有设定根据设定更新
            temread = ReadIni("DBVREG", "Showrate", InfPath);
            if (temread.Length > 0)
            {
                IC51Reg.Showrate = Convert.ToDouble(temread);
            }
            //===DBV 51 reg cfg get end ===============

            //===Demura function Btn strat===============


            temread = ReadIni("Demura", "Demura_BtnNum", InfPath);
            if (temread.Length > 0)
            {
                IC_funBtn_num = Convert.ToInt32(temread);
                for (int i = 0; i < IC_funBtn_num; i++)
                {
                    IC_demura[i] = new BtnType();
                    IC_demura[i].Btnname = ReadIni("Demura", "Demura_Btn" + (i + 1) + "_name", InfPath);
                    temread = ReadIni("Demura", "Demura_Btn" + (i + 1) + "_code", InfPath).ToUpper();
                    if ((temread.Length > 5) && (temread.Substring(0, 8) == "2KSCRIPT"))
                    {
                    }
                    IC_demura[i].BtnCode = ReadIni("Demura", "Demura_Btn" + (i + 1) + "_code", InfPath);
                }

            }

            //===Demura function Btn end===============

        }

        private void CheckdefualtCfg()
        {
            string Userpath = Application.StartupPath + "\\HF_Autogamma";

            if (!Directory.Exists(Userpath))
            {
                Directory.CreateDirectory(Userpath);
            }

            Userpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG";
            //            defualtinfPath = Userpath + "\\deafault.Gamma";
            if (!Directory.Exists(Userpath))
            {
                Directory.CreateDirectory(Userpath);
            }

            string defualtinfPath = Userpath + "\\Gamma_CFG";
            if (!Directory.Exists(defualtinfPath)) //不存在
            {
                Directory.CreateDirectory(defualtinfPath);//不存在则创建
                defualtinfPath = Userpath + "\\2K_CFG.inf";
                bool result = WritePrivateProfileString("ProductInfo", "Author", "Visionox_Hefei_System_tearm", defualtinfPath);
                result = WritePrivateProfileString("ProductInfo", "Version", "2020.10", defualtinfPath);
                result = WritePrivateProfileString("Lastlog", "InitalCFGPath", "", defualtinfPath);
                result = WritePrivateProfileString("Lastlog", "ICCFGPath", "", defualtinfPath);
                result = WritePrivateProfileString("Lastlog", "ScriptPath", "", defualtinfPath);
                result = WritePrivateProfileString("Lastlog", "GammaDataPath", "", defualtinfPath);
                result = WritePrivateProfileString("Lastlog", "PatternPath", "", defualtinfPath);

                defualtinfPath = Userpath + "\\2K_Gamma.inf";
                result = WritePrivateProfileString("ProductInfo", "Author", "Visionox_Hefei_System_tearm", defualtinfPath);
                result = WritePrivateProfileString("ProductInfo", "Version", "2020.10", defualtinfPath);
                result = WritePrivateProfileString("ProjectInfo", "ProjectNum", "0", defualtinfPath);
                result = WritePrivateProfileString("ProjectInfo", "ProjectList", "0", defualtinfPath);
                result = WritePrivateProfileString("ProjectInfo", "List1", "", defualtinfPath);
                result = WritePrivateProfileString("ProjectInfo", "List2", "", defualtinfPath);
                result = WritePrivateProfileString("ProjectInfo", "List3", "", defualtinfPath);
            }
            defualtinfPath = Userpath + "\\DefualtScript";   //加载script 历史记录到debug 框
            if (!Directory.Exists(defualtinfPath)) //不存在
            { Directory.CreateDirectory(defualtinfPath); }//不存路径在则创建 
            else
            {
                string fname = Userpath + "\\2K_CFG.inf";
                for (int i = 0; i < 40; i++)
                {
                    defualtinfPath = Userpath + "\\DefualtScript\\Script-" + i + "_code.txt";
                    if (File.Exists(defualtinfPath)) //存在脚本则加载到
                    {
                        ScriptSavestring[i] = loadScriptFromfile(defualtinfPath);
                        listBox_SendScript.Items[i] = ReadIni("Lastlog", "DefualtScript" + i.ToString(), fname);
                        //Demura页面窗口内容初始化
                        if (i<8)
                        {
                            switch (i)
                            {
                                case 0:
                                    textBox_Scrinp1.Text = ScriptSavestring[i];
                                    break;
                                case 1:
                                    textBox_Scrinp2.Text = ScriptSavestring[i];
                                    break;
                                case 2:
                                    textBox_Scrinp3.Text = ScriptSavestring[i];
                                    break;
                                case 3:
                                    textBox_Scrinp4.Text = ScriptSavestring[i];
                                    break;
                                case 4:
                                    textBox_Scrinp5.Text = ScriptSavestring[i];
                                    break;
                                case 5:
                                    textBox_Scrinp6.Text = ScriptSavestring[i];
                                    break;
                                case 6:
                                    textBox_Scrinp7.Text = ScriptSavestring[i];
                                    break;
                                case 7:
                                    textBox_Scrinp8.Text = ScriptSavestring[i];
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
                //text_script_send_all.Text = ScriptSavestring[0];
            }
            defualtinfPath = Userpath + "\\2K_CFG.inf";
            ICGT.ProjectName = ReadIni("Lastlog", "DefualtProjectName", defualtinfPath);

            DirectoryInfo folder = new DirectoryInfo(Userpath + "\\Gamma_CFG");
            int temIndex = 0, recordIndex = -1;
            foreach (FileInfo file in folder.GetFiles("*.Gamma")) //枚举库文件下的所有gamma 文件show 到列表里
            {
                //Console.WriteLine(file.FullName);
                temIndex += 1;
                ComboBox_Porject.Items.AddRange(new object[] { file.Name });
                if (file.Name == ICGT.ProjectName) recordIndex = temIndex;
            }
            if (recordIndex >= 0)
            {
                ComboBox_Porject.SelectedIndex = recordIndex;
                GGourpBox.Text = ICGT.ICName;
            }

            defualtinfPath = Userpath + "\\Lastlog.inf";
            textBox2.Text = ReadIni("Lastlog", "2KPicPath", defualtinfPath);

            /*
            if (File.Exists(defualtinfPath))
            {
                GTcfgPath = defualtinfPath;
                GetgammCfg(1);// 加载cfg 并默认group1             
                ShowArray();
            }*/
        }
        private void ComboBox_Porject_Click(object sender, EventArgs e)
        {
            string defualtinfPath = "";
            string Userpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG";
            string fname = Userpath + "\\2K_CFG.inf";
            for (int i = 0; i < 40; i++)
            {
                defualtinfPath = Userpath + "\\DefualtScript\\Script-" + i + "_code.txt";
                if (File.Exists(defualtinfPath)) //存在脚本则加载到
                {
                    ScriptSavestring[i] = loadScriptFromfile(defualtinfPath);
                    listBox_SendScript.Items[i] = ReadIni("Lastlog", "DefualtScript" + i.ToString(), fname);
                }
            }
        }
        private void MakeArray(int numarray) //预加载 控件
        {
            int m;
            LabTitleArry = new Label[40];
            LabArry = new Label[numarray];
            NumArry = new NumericUpDown[numarray];
            TextArry = new TextBox[3, Maxarry];
            BtnArry = new Button[40];
            Btn_fun_Arry = new Button[100];
            RadioArry = new RadioButton[200];
            //ICGT.GGN_Name[i - 1]
            for (int j = 0; j < 10; j++)
            {
                m = j * 2;
                BtnArry[j * 2] = new Button();
                BtnArry[m].Click += new System.EventHandler(this.BtnArry_Click); //统一的事件处理   // tabPage2.Controls.Add(BtnArry[k]); //在窗体上呈现控件

                BtnArry[m].Visible = false;
                GGourpBox.Controls.Add(BtnArry[m]); //在窗体上呈现控件

                m = j * 2 + 1;
                BtnArry[m] = new Button();
                BtnArry[m].Click += new System.EventHandler(this.BtnArry_Click); //统一的事件处理   // tabPage2.Controls.Add(BtnArry[k]); //在窗体上呈现控件

                BtnArry[m].Visible = false;
                GGourpBox.Controls.Add(BtnArry[m]); //在窗体上呈现控件
            }
            for (int j = 0; j < 3; j++)
            {
                for (int i = 0; i < Maxarry; i++)
                {
                    int k = j * Maxarry + i;
                    NumArry[k] = new NumericUpDown();
                    NumArry[k].Name = "NumArry";
                    NumArry[k].Hexadecimal = true;
                    NumArry[k].Visible = false;
                    NumArry[k].Size = new System.Drawing.Size(45, 24);
                    NumArry[k].Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 134);
                    tabPage2.Controls.Add(NumArry[k]); //在窗体上呈现控件

                    LabArry[k] = new Label();
                    LabArry[k].Name = "LabArry";
                    LabArry[k].Visible = false;
                    LabArry[k].Size = new System.Drawing.Size(2, 19);
                    tabPage2.Controls.Add(LabArry[k]); //在窗体上呈现控件

                    TextArry[j, i] = new TextBox();
                    TextArry[j, i].Name = "TargetTextArry";
                    TextArry[j, i].Visible = false;
                    TextArry[j, i].Size = new System.Drawing.Size(38, 24);
                    tabPage2.Controls.Add(TextArry[j, i]); //在窗体上呈现控件
                }
            }
            for (int i = 0; i < 40; i++) //预加载RadioArry_Click
            {
                m = i;
                LabTitleArry[i] = new Label();
                LabTitleArry[i].Name = "LabTitleArry";
                LabTitleArry[i].Visible = false;
                LabTitleArry[i].Size = new System.Drawing.Size(40, 23);
                tabPage2.Controls.Add(LabTitleArry[i]); //在窗体上呈现控件

            }
            for (int i = 0; i < 20; i++) //预加载Btn_demura_Click
            {
                Btn_fun_Arry[i] = new Button();
                Btn_fun_Arry[i].Size = new System.Drawing.Size(360, 20);
                Btn_fun_Arry[i].Tag = i;
                Btn_fun_Arry[i].Click += new System.EventHandler(this.Btn_fun_Arry_Click); //统一的事件处理
                GourpBox_Demura.Controls.Add(Btn_fun_Arry[i]);
                Btn_fun_Arry[i].Visible = false;

            }
            //Btn_demura

        }
        //show Gamma Group box ,只是在加载Gamma cfg 文件时触发
        private void ShowGGNBox(string InfPath)
        {
            int k = 0;
            int loc_x = 0, loc_y = 0;
            string btntag = "";

            Color Bccolor = Color.FromArgb(255, 0, 0, 0);
            Color Frcolor = Color.Black;
            //show  W/R/G/B buttrn
            for (int j = 0; j < 5; j++)//show  W/R/G/B buttrn
            {
                string btntext = "Red_";
                //offsetx = 10 + 90 * j;

                if (j == 0) { btntext = "W_"; Frcolor = Color.White; Bccolor = Color.FromArgb(180, 255, 255, 255); }
                if (j == 1) { btntext = "R_"; Frcolor = Color.Black; Bccolor = Color.FromArgb(180, 255, 180, 180); }
                if (j == 2) { btntext = "G_"; Frcolor = Color.Black; Bccolor = Color.FromArgb(180, 180, 255, 180); }
                if (j == 3) { btntext = "B_"; Frcolor = Color.White; Bccolor = Color.FromArgb(180, 180, 180, 255); }

                for (int i = 0; i < 2; i++)
                {
                    k = j * 2 + i;
                    loc_x = 5 + j * 50;
                    loc_y = 15 + i * 30;
                    btntag = k.ToString();
                    BtnArry[k].Size = new System.Drawing.Size(45, 25);

                    string btnname = btntext + "W";
                    if (i == 1) { btnname = btntext + "R"; }
                    if (j == 4)
                    {
                        BtnArry[k].Size = new System.Drawing.Size(95, 25);
                        loc_x = 5 + i * 100;
                        loc_y = 15 + (j - 2) * 30;
                        btnname = "Calc_XYZ";
                        // btntag = "";
                        if (i == 1) { btnname = "Enter_GammaMode"; }
                        //
                        //if (i == 1) { btnname = "Limit_Lv_x_y"; }
                    }

                    BtnArry[k].Name = btnname;
                    BtnArry[k].Text = btnname;
                    //BtnArry[k].Size = new System.Drawing.Size(45, 25);
                    BtnArry[k].Location = new System.Drawing.Point(loc_x, loc_y);
                    BtnArry[k].Tag = btntag;
                    BtnArry[k].BackColor = Bccolor;
                    BtnArry[k].Visible = true;
                }
            }

            string[] temarray, subarray;
            int nodeacount = 0;
            string GGN_index;
            treeView_GammaGroupN.Nodes.Clear();
            if (ICGT.GGSectionTree != "")
            {
                temarray = ICGT.GGSectionTree.Split(';');
                //int GGNum = Convert.ToInt32(temarray[0]);
                int GGNum = temarray.Length;
                for (int i = 1; i < GGNum; i++)
                {
                    GGN_index = i.ToString();
                    subarray = temarray[i].Split(',');
                    if (subarray.Length <= 1) continue;
                    if (subarray.Length > 2) GGN_index = subarray[2];
                    TreeNode tempnode1 = new TreeNode(subarray[0]);

                    tempnode1.Tag = "$" + GGN_index;
                    treeView_GammaGroupN.Nodes.Add(tempnode1);
                    nodeacount += 1;

                    int subGGNum = Convert.ToInt32(subarray[1]);
                    for (int j = 1; j <= subGGNum; j++)
                    {

                        string subGGSection = "GGN_" + GGN_index + "_" + j.ToString();
                        string subname = ReadIni(subGGSection, "GGN_Name", InfPath);
                        TreeNode tempnode2 = new TreeNode(subname);
                        tempnode2.Tag = subGGSection;
                        tempnode1.Nodes.Add(tempnode2);

                        // treeView_GammaGroupN.Nodes[nodeacount].Tag = subGGSection;
                        nodeacount += 1;
                    }
                }
                //  ICGT.GGSectionTuneNum = nodeacount;
                //treeView_GammaGroupN.ExpandAll();

                //GGourpBox.Size = new System.Drawing.Size(200, offsety + 20 + 11 * 22);
            }


        }

        //根据gamma cfg 显示加载gamma 参数 按钮
        private void ShowArray()
        {
            int k = 0, lmax, lmaxrecord;
            int HeighIndex = (tabControl1.Height - 25) / 27 - 2;
            Color Bccolor = Color.FromArgb(255, 0, 0, 0);
            Color Frcolor = Color.Black;
            Maxarry = ICGT.NodeEffetNum;
            lmax = Maxarry * 3;
            lmaxrecord = MaxarryRecord * 3;
            ComboBox_Porject.SelectedText = ICGT.ProjectName;
            if (lmax > 0)
            {
                if ((lmax < lmaxrecord))
                {
                    for (int i = lmax; i < lmaxrecord; i++)
                    {
                        LabArry[i].Visible = false;
                        NumArry[i].Visible = false;
                    }
                    for (int i = Maxarry; i < MaxarryRecord; i++)
                    {
                        TextArry[0, i].Visible = false;
                        TextArry[1, i].Visible = false;
                        TextArry[2, i].Visible = false;
                    }
                }
                else if ((lmax > lmaxrecord))
                {
                    for (int i = lmaxrecord; i < lmax; i++)
                    {
                        LabArry[i] = new Label();
                        NumArry[i] = new NumericUpDown();
                        NumArry[i].Visible = false;
                        MaxarryRecord = Maxarry;
                    }
                }
                //if ((BtnArry[4].Tag  =="XYZ") || (BtnArry[4].Tag == "Lvxy"))
                //{
                //}

                int m, n;

                int LabTitlenum = 0;
                for (int j = 0; j < 3; j++)//num and lable
                {
                    string btntext = "Red_";
                    if (j == 0) { btntext = "Red"; Frcolor = Color.FromArgb(240, 200, 200); Bccolor = Color.FromArgb(255, 0, 0); }
                    if (j == 1) { btntext = "Green"; Frcolor = Color.FromArgb(200, 240, 200); Bccolor = Color.FromArgb(0, 255, 0); }
                    if (j == 2) { btntext = "Blue"; Frcolor = Color.FromArgb(200, 200, 240); Bccolor = Color.FromArgb(0, 0, 255); }
                    for (int i = 0; i < Maxarry; i++)
                    {

                        offsetx = 10 + i / HeighIndex * 320;
                        offsety = 30 - i / HeighIndex * 28 * HeighIndex;
                        k = j * Maxarry + i;

                        if (i % Maxarry == 0)
                        {
                            LabTitleArry[LabTitlenum].Location = new System.Drawing.Point(offsetx + 32 + 52 * j, 10);
                            LabTitleArry[LabTitlenum].Text = btntext;
                            LabTitleArry[LabTitlenum].Visible = true;
                            LabTitleArry[LabTitlenum].BackColor = Frcolor;
                            LabTitlenum += 1;
                        }
                        NumArry[k].Location = new System.Drawing.Point(offsetx + 32 + 52 * j, offsety + 28 * i);
                        NumArry[k].Maximum = MaxNodeValue_A[i];
                        NumArry[k].ForeColor = Color.Black;
                        NumArry[k].Visible = true;

                        LabArry[k].Location = new System.Drawing.Point(offsetx + 30 + 52 * j, offsety + 2 + 28 * i);
                        LabArry[k].BackColor = Bccolor;
                        LabArry[k].Visible = true;
                        LabArry[k].Size = new System.Drawing.Size(2, 19);

                        // tabPage2.Controls.Add(LabArry[k]); //在窗体上呈现控件
                        if (i % Maxarry == 0)
                        {
                            LabTitleArry[LabTitlenum].Location = new System.Drawing.Point(offsetx + 185 + 40 * j, 10);
                            if (j == 0) { LabTitleArry[LabTitlenum].Text = "X"; }
                            else if (j == 1) { LabTitleArry[LabTitlenum].Text = "Y"; }
                            else if (j == 2) { LabTitleArry[LabTitlenum].Text = "Z"; }

                            LabTitleArry[LabTitlenum].BackColor = Frcolor;
                            LabTitleArry[LabTitlenum].Visible = true;
                            LabTitlenum += 1;
                        }


                        TextArry[j, i].Location = new System.Drawing.Point(offsetx + 185 + 40 * j, offsety + 2 + 28 * i);
                        //TextArry[j, i].BackColor = Frcolor;
                        TextArry[j, i].Visible = true;
                        // tabPage2.Controls.Add(TextArry[j, i]); //在窗体上呈现控件
                    }
                }
                for (int i = 0; i < Maxarry; i++)//长lable
                {
                    k = 3 * Maxarry + 1 + i;
                    offsetx = 10 + i / HeighIndex * 320;
                    offsety = 30 - i / HeighIndex * 28 * HeighIndex;
                    LabArry[k].Location = new System.Drawing.Point(offsetx - 5 + 90 * 0, offsety - 2 + 28 * i);
                    LabArry[k].Size = new System.Drawing.Size(320, 26);
                    //LabArry[k].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                    LabArry[k].Font = new System.Drawing.Font("微软雅黑", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 134);

                    LabArry[k].ForeColor = Color.Black;
                    if (i % 2 == 0)
                    { LabArry[k].BackColor = Color.FromArgb(235, 235, 235); }
                    //{ LabArry[k].BackColor = Color.FromArgb(210, 222, 239); }
                    else
                    { LabArry[k].BackColor = Color.FromArgb(234, 239, 247); }

                    LabArry[k].Text = NodePos_A[i].ToString();
                    LabArry[k].Visible = true;
                    tabPage2.Controls.Add(LabArry[k]); //在窗体上呈现控件

                }

                if (IC_funBtn_num > 0)
                {
                    k = 130;
                    for (int i = 0; i < IC_funBtn_num; i++)
                    {
                        m = (i + 2) >> 1;
                        n = (i + 2) % 2;
                        Btn_fun_Arry[i].Text = IC_demura[i].Btnname;
                        Btn_fun_Arry[i].Size = new System.Drawing.Size(140, 28);
                        Btn_fun_Arry[i].Location = new System.Drawing.Point(20 + n * 150, 226 + m * 35);
                        Btn_fun_Arry[i].Visible = true;

                        //m = (i ) >> 1;
                        //n = (i ) % 2;
                        //RadioArry[i].Text = IC_demura[i].Btnname;
                        //RadioArry[i].Size = new System.Drawing.Size(140, 28);
                        //RadioArry[i].Location = new System.Drawing.Point(20 + n * 200, 26 + m * 35);
                        //RadioArry[i].BackColor = Color.LightGray  ;
                        //RadioArry[i].Visible = true;

                    }
                }

                GGourpBox.Left = tabControl1.Width - GGourpBox.Width - 30;
            }

        }

        private int StringGray(string str)
        {
            string newstr = str.Trim();          //去字符串头尾空格	
            newstr = newstr.Substring(1);        //去掉第一个字符
            if (int.TryParse(newstr, out int result))//string转int
                return result;
            else
                return 256;
        }


        //判断两不同长度字符串是否相等
        private bool IsString(string str1, string str2)   //str1为比对字符串，str2为目标字符串
        {
            int IsNum = 0;
            int str1_len = 0, str2_len = 0;

            str1 = str1.Trim();          //去字符串头尾空格	
            str1 = str1.ToLower();    //string转小写
            str1_len = str1.Length;

            str2 = str2.ToLower();
            str2_len = str2.Length;

            //单循环查找相同字符的首序号
            for (int i = 0; i < str1_len; i++)
            {
                if ((str1[i] == str2[0]) &&         //首字符
                    ((str1_len - i) >= str2_len))   //比对长度
                {
                    IsNum = 0;
                    //循环判断两字符串是否存在相等
                    for (int j = 0; j < str2_len; j++)
                    {
                        if (str1[i + j] == str2[j])
                        {
                            IsNum++;
                            if (IsNum == str2_len)//判断字符相等的个数
                            {
                                return true;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            return false;
        }


        //切换新的.gamma文件初始化
        private void filegamma_init()
        {
            NowClickGroupNum = 0;//当前所有点击的Group数量
            NowClickGroup = 0; //点击的Group，当前数组的位置
            for (int j = 0; j < Arr_NowClickGroup.Length; j++) { Arr_NowClickGroup[j] = 0; }
            Btn_id = 1000; //Btn的id
            shortCut_Key_Fun.Checked = false;
            Label_Status_Lum.Text = "               ";
            Label_Status_Gray.Text = "               ";
            Label_Status_Fre.Text = "               ";
            Label_Status_IP.Text = "               ";
            Label_Status_Gray.BackColor = System.Drawing.SystemColors.MenuBar;
            Label_Status_Lum.BackColor = System.Drawing.SystemColors.MenuBar;
            Label_Status_Fre.BackColor = System.Drawing.SystemColors.MenuBar;
            Label_Status_IP.BackColor = System.Drawing.SystemColors.MenuBar;
            Btn_id_His = 1000;
        }

        //鼠标点击定义的.gamma文件生产的按钮，触发快捷键数据变更
        private void ShortKey_DataChange_Click(object sender, System.EventArgs e)
        {
            //点击事件，触发快捷键数据变更
            MinNum = 0;
            for (int i = 0; i < GroupNum; i++) //求当前Group内Btn_id的最大最小值
            {
                if ((Btn_id >= MinNum) && (Btn_id <= MinNum + Arr_BtnNum[i] - 1))
                {
                    MaxNum = MinNum + Arr_BtnNum[i] - 1;
                    break;
                }
                MinNum += Arr_BtnNum[i];
            }

            if (NowClickGroupNum == 0) //btn未被点击过
            {
                NowClickGroupNum = 1;
                NowClickGroup = 0;
                Arr_NowClickGroup[NowClickGroup] = Btn_id;
            }
            else //btn被点击过
            {
                bool Flag_InGroup = false;
                for (int j = 0; j < NowClickGroupNum; j++) //Btn_id在Arr_NowClickGroup的组内范围
                {
                    if ((Arr_NowClickGroup[j] >= MinNum) && (Arr_NowClickGroup[j] <= MaxNum))
                    {
                        NowClickGroup = j;
                        Arr_NowClickGroup[NowClickGroup] = Btn_id;
                        Flag_InGroup = true;
                        break;
                    }
                }
                if (!Flag_InGroup) //Btn_id不在Arr_NowClickGroup的组内范围
                {
                    int GroupVal = 0;
                    NowClickGroupNum += 1;
                    Arr_NowClickGroup[NowClickGroupNum - 1] = Btn_id;
                    for (int k = NowClickGroupNum - 1; k > 0; k--) //排序
                    {
                        if (Arr_NowClickGroup[k] < Arr_NowClickGroup[k - 1])
                        {
                            GroupVal = Arr_NowClickGroup[k - 1];
                            Arr_NowClickGroup[k - 1] = Arr_NowClickGroup[k];
                            Arr_NowClickGroup[k] = GroupVal;
                        }
                    }
                    for (int h = 0; h < NowClickGroupNum; h++)
                    {
                        if (Arr_NowClickGroup[h] == Btn_id)
                        {
                            NowClickGroup = h;
                            break;
                        }
                    }
                }
            }
            //显示按钮背景颜色
            Radio_Status_Display(sender, e);
        }

        private void shortCut_Key_Fun_CheckedChanged(object sender, EventArgs e)
        {

        }
        private void shortCut_Key_Fun_MouseEnter(object sender, EventArgs e)
        {
            //ToolTip p = new ToolTip();
            //p.ShowAlways = true;
            //p.SetToolTip(this.shortCut_Key_Fun, "勾选后开启下方8个窗体write快捷键，1—8窗体分别对应QWERTYUI ASDFGHJK");
        }
        private void shortCut_Key_Fun_Leave(object sender, EventArgs e)
        {
            shortCut_Key_Fun.Checked = !shortCut_Key_Fun.Checked;
        }


        private void MinMax_Fun()
        {
            MinNum = 0;
            for (int i = 0; i < GroupNum; i++) //求当前Group内Btn_id的最大最小值
            {
                if ((Btn_id >= MinNum) && (Btn_id <= MinNum + Arr_BtnNum[i] - 1))
                {
                    MaxNum = MinNum + Arr_BtnNum[i] - 1;
                    break;
                }
                MinNum += Arr_BtnNum[i];
            }
        }

        int GroupNum = 0; //当前所有Group数量
        int[] Arr_BtnNum = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //记录每个Group的Btn数

        int NowClickGroupNum = 0;//当前所有点击的Group数量
        int NowClickGroup = 0; //点击的Group，当前数组的位置
        int[] Arr_NowClickGroup = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //点击的各行的Group记录的Btn_id

        int Btn_id = 0; //Btn的id
        int MinNum = 0, MaxNum = 0; //Btn_id所在组的最大最小值
        private void shortCut_Key_Fun_KeyDown(object sender, KeyEventArgs e)
        {
            if (shortCut_Key_Fun.Checked == true)
            {
                if (e.KeyCode == Keys.W)
                {
                    if (NowClickGroup >= 1)
                    {
                        NowClickGroup -= 1;
                        Btn_id = Arr_NowClickGroup[NowClickGroup];
                        textBox_Function.Text = Function_Btn[Btn_id].BtnCode; //显示代码
                        MinMax_Fun();
                    }
                }
                else if (e.KeyCode == Keys.S)
                {
                    
                    if (NowClickGroup < NowClickGroupNum - 1)
                    {
                        NowClickGroup += 1;
                        Btn_id = Arr_NowClickGroup[NowClickGroup];
                        textBox_Function.Text = Function_Btn[Btn_id].BtnCode; //显示代码
                        MinMax_Fun();
                    }
                }

                else if (e.KeyCode == Keys.A)
                {
                    MinMax_Fun();
                    if ((Btn_id > MinNum) && (Btn_id <= MaxNum))
                    {
                        Btn_id -= 1;
                        Arr_NowClickGroup[NowClickGroup] = Btn_id;
                        textBox_Function.Text = Function_Btn[Btn_id].BtnCode; //显示代码
                        string ss = Write99Comport_Script(Function_Btn[Btn_id].BtnCode); //写入代码
                    }
                    else if (Btn_id == MinNum)
                    {
                        Btn_id = MaxNum;
                        Arr_NowClickGroup[NowClickGroup] = Btn_id;
                        textBox_Function.Text = Function_Btn[Btn_id].BtnCode; //显示代码
                        string ss = Write99Comport_Script(Function_Btn[Btn_id].BtnCode); //写入代码
                    }
                }
                else if (e.KeyCode == Keys.D)
                {
                    MinMax_Fun();
                    if ((Btn_id >= MinNum) && (Btn_id < MaxNum))
                    {
                        Btn_id += 1;
                        Arr_NowClickGroup[NowClickGroup] = Btn_id;
                        textBox_Function.Text = Function_Btn[Btn_id].BtnCode; //显示代码
                        string ss = Write99Comport_Script(Function_Btn[Btn_id].BtnCode); //写入代码
                    }
                    else if (Btn_id == MaxNum)
                    {
                        Btn_id = MinNum;
                        Arr_NowClickGroup[NowClickGroup] = Btn_id;
                        textBox_Function.Text = Function_Btn[Btn_id].BtnCode; //显示代码
                        string ss = Write99Comport_Script(Function_Btn[Btn_id].BtnCode); //写入代码

                    }
                }
                else if ((e.KeyCode == Keys.Q) || (e.KeyCode == Keys.E))
                {
                    textBox_Function.Text = Function_Btn[Btn_id].BtnCode; //显示代码
                    string ss = Write99Comport_Script(Function_Btn[Btn_id].BtnCode); //写入代码
                }


                else if ((e.KeyCode == Keys.D1) || (e.KeyCode == Keys.NumPad1))
                {
                    ScrinptSend_Function(sender, e, 1);
                }
                else if ((e.KeyCode == Keys.D2) || (e.KeyCode == Keys.NumPad2))
                {
                    ScrinptSend_Function(sender, e, 2);
                }
                else if ((e.KeyCode == Keys.D3) || (e.KeyCode == Keys.NumPad3))
                {
                    ScrinptSend_Function(sender, e, 3);
                }
                else if ((e.KeyCode == Keys.D4) || (e.KeyCode == Keys.NumPad4))
                {
                    ScrinptSend_Function(sender, e, 4);
                }
                else if ((e.KeyCode == Keys.D5) || (e.KeyCode == Keys.NumPad5))
                {
                    ScrinptSend_Function(sender, e, 5);
                }
                else if ((e.KeyCode == Keys.D6) || (e.KeyCode == Keys.NumPad6))
                {
                    ScrinptSend_Function(sender, e, 6);
                }
                else if ((e.KeyCode == Keys.D7) || (e.KeyCode == Keys.NumPad7))
                {
                    ScrinptSend_Function(sender, e, 7);
                }
                else if ((e.KeyCode == Keys.D8) || (e.KeyCode == Keys.NumPad8))
                {
                    ScrinptSend_Function(sender, e, 8);
                }
                else if (e.KeyCode == Keys.Escape)
                {
                    shortCut_Key_Fun_Leave(sender,e);
                }
                else
                {
                    MessageBox.Show("该键位没有设置快捷键");
                }

                //显示按钮背景颜色
                Radio_Status_Display(sender, e); 
                //显示当前状态
                Label_Status_Display(sender, e);
            }
        }

        Color NowClickColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
        Color HisClickColor = System.Drawing.Color.FromArgb(((int)(((byte)(142)))), ((int)(((byte)(221)))), ((int)(((byte)(255)))));
        //Color HisClickColor = System.Drawing.Color.FromArgb(((int)(((byte)(104)))), ((int)(((byte)(209)))), ((int)(((byte)(255)))));
        int Btn_id_His = 1000;
        private void Radio_Status_Display(object sender, EventArgs e)
        {
            //上下移动
            if (((Btn_id_His < MinNum) || (Btn_id_His > MaxNum)) && (Btn_id_His != 1000))
            {
                RadioArry[Btn_id_His].BackColor = HisClickColor;
            }
            //显示当前状态
            if (Btn_id != 1000)
            {
                for (int i = MinNum; i <= MaxNum; i++)
                {
                    RadioArry[i].BackColor = Color.LightGray;
                }
                RadioArry[Btn_id].BackColor = NowClickColor;
            }
            Btn_id_His = Btn_id;
        }

        private void Label_Status_Display(object sender, EventArgs e)
        {
            //显示当前状态
            if(Btn_id != 1000)
            {
                string textBox_name = Function_Btn[Btn_id].Btnname;
                if ((IsString(textBox_name, "W") || IsString(textBox_name, "R") || IsString(textBox_name, "G") || IsString(textBox_name, "B")) &&
                    ((StringGray(textBox_name) >= 0) && (StringGray(textBox_name) <= 255)))
                {
                    Label_Status_Gray.BackColor = NowClickColor;
                    Label_Status_Lum.BackColor = HisClickColor;
                    Label_Status_Fre.BackColor = HisClickColor;
                    Label_Status_IP.BackColor = HisClickColor;
                    Label_Status_Gray.Text = Function_Btn[Btn_id].Btnname;
                }

                else if (IsString(textBox_name, "NOR") || IsString(textBox_name, "APL") || IsString(textBox_name, "HDR") || IsString(textBox_name, "HBM") || IsString(textBox_name, "nit"))
                {
                    Label_Status_Gray.BackColor = HisClickColor;
                    Label_Status_Lum.BackColor = NowClickColor;
                    Label_Status_Fre.BackColor = HisClickColor;
                    Label_Status_IP.BackColor = HisClickColor;
                    Label_Status_Lum.Text = Function_Btn[Btn_id].Btnname;
                }
                else if (IsString(textBox_name, "HZ"))
                {
                    Label_Status_Gray.BackColor = HisClickColor;
                    Label_Status_Lum.BackColor = HisClickColor;
                    Label_Status_Fre.BackColor = NowClickColor;
                    Label_Status_IP.BackColor = HisClickColor;
                    Label_Status_Fre.Text = Function_Btn[Btn_id].Btnname;
                }
                else if ((IsString(textBox_name, "ON")) || (IsString(textBox_name, "OFF")))
                {
                    Label_Status_Gray.BackColor = HisClickColor;
                    Label_Status_Lum.BackColor = HisClickColor;
                    Label_Status_Fre.BackColor = HisClickColor;
                    Label_Status_IP.BackColor = NowClickColor;
                    Label_Status_IP.Text = Function_Btn[Btn_id].Btnname;
                }
            } 
        }

        
        private void btnColor_Click(int ClickNum)
        {
            Color[] colors = new Color[] { Color.White,Color.White,Color.White,Color.White,Color.White,Color.White,Color.White,Color.White,    Color.White };
            if((ClickNum >= 0) && (ClickNum < 8)) //小于8时，给目标按键颜色，等于8时，全为白色
            {
                colors[ClickNum] = NowClickColor;
            }
            this.btn_ScrinpSend1.BackColor = colors[0];
            this.btn_ScrinpSend2.BackColor = colors[1];
            this.btn_ScrinpSend3.BackColor = colors[2];
            this.btn_ScrinpSend4.BackColor = colors[3];
            this.btn_ScrinpSend5.BackColor = colors[4];
            this.btn_ScrinpSend6.BackColor = colors[5];
            this.btn_ScrinpSend7.BackColor = colors[6];
            this.btn_ScrinpSend8.BackColor = colors[7];
        }
        private void ScrinptSend_Function(object sender, EventArgs e, int btnClickNum)
        {
            btnClickNum -=1;
            switch (btnClickNum)
            {
                case 0:
                    text_script_send_all.Text = textBox_Scrinp1.Text;
                    break;
                case 1:
                    text_script_send_all.Text = textBox_Scrinp2.Text;
                    break;
                case 2:
                    text_script_send_all.Text = textBox_Scrinp3.Text;
                    break;
                case 3:
                    text_script_send_all.Text = textBox_Scrinp4.Text;
                    break;
                case 4:
                    text_script_send_all.Text = textBox_Scrinp5.Text;
                    break;
                case 5:
                    text_script_send_all.Text = textBox_Scrinp6.Text;
                    break;
                case 6:
                    text_script_send_all.Text = textBox_Scrinp7.Text;
                    break;
                case 7:
                    text_script_send_all.Text = textBox_Scrinp8.Text;
                    break;
                default: break;
            }
            if((btnClickNum>=0) && (btnClickNum <=7))
            {
                btnColor_Click(btnClickNum);
                text_script_send_all.Tag = btnClickNum.ToString(); ;
                button4_Click(sender, e);
                text_listTitle.Text = Convert.ToString(listBox_SendScript.Items[btnClickNum]);
            }
        }
        private void btnSend1_Click(object sender, EventArgs e)
        {
            ScrinptSend_Function(sender, e, 1);
        }
        private void btnSend2_Click(object sender, EventArgs e)
        {
            ScrinptSend_Function(sender, e, 2);
        }
        private void btnSend3_Click(object sender, EventArgs e)
        {
            ScrinptSend_Function(sender, e, 3);
        }
        private void btnSend4_Click(object sender, EventArgs e)
        {
            ScrinptSend_Function(sender, e, 4);
        }
        private void btnSend5_Click(object sender, EventArgs e)
        {
            ScrinptSend_Function(sender, e, 5);
        }
        private void btnSend6_Click(object sender, EventArgs e)
        {
            ScrinptSend_Function(sender, e, 6);
        }
        private void btnSend7_Click(object sender, EventArgs e)
        {
            ScrinptSend_Function(sender, e, 7);
        }
        private void btnSend8_Click(object sender, EventArgs e)
        {
            ScrinptSend_Function(sender, e, 8);
        }
        private void textBox_Scrinp1_TextChanged(object sender, EventArgs e)
        {

        }
        private void textBox_Scrinp2_TextChanged(object sender, EventArgs e)
        {

        }
        private void textBox_Scrinp3_TextChanged(object sender, EventArgs e)
        {

        }
        private void textBox_Scrinp4_TextChanged(object sender, EventArgs e)
        {

        }
        private void textBox_Scrinp5_TextChanged(object sender, EventArgs e)
        {

        }
        private void textBox_Scrinp6_TextChanged(object sender, EventArgs e)
        {

        }
        private void textBox_Scrinp7_TextChanged(object sender, EventArgs e)
        {

        }
        private void textBox_Scrinp8_TextChanged(object sender, EventArgs e)
        {

        }
        private void Label_Status_Lum_Display(object sender, EventArgs e)
        {

        }
        private void Label_Status_Gray_Display(object sender, EventArgs e)
        {

        }
        private void Label_Status_Fre_Display(object sender, EventArgs e)
        {

        }
        private void Label_Status_IP_Display(object sender, EventArgs e)
        {

        }
        private void textBox_Function_TextChanged(object sender, EventArgs e)
        {

        }
        private void textBox16_TextChanged(object sender, EventArgs e)
        {

        }

        private void text_script_send_all_TextChanged(object sender, EventArgs e)
        {

        }

        private void GourpBox_Function_Enter(object sender, EventArgs e)
        {

        }

        private void lab_CASDK_Lv_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void Label_Status_IP_Click(object sender, EventArgs e)
        {

        }

        private void Label_Status_Fre_Click(object sender, EventArgs e)
        {

        }

        private void Label_Status_Lum_Click(object sender, EventArgs e)
        {

        }

        private void Label_Status_Gray_Click(object sender, EventArgs e)
        {

        }
        private void butExplain_Click(object sender, EventArgs e)
        {
            MessageBox.Show(
                "1. 快捷键：\n" +
                "    上下左右：WSAD键\n" +
                "    上下移动后，默认不进行写入，可通过Q或者E键写入\n" +
                "    右侧窗口写入：1-8键\n" + 
                "    退出快捷键：Esc键\n\n" + 
                "2. xxx.gamma：\n" + 
                "    可通过右上角 “项目：” 添加相应项目gamma文本\n" +
                "    xxx.gamma模板参考该软件本地路径下：\n" +
                "    根目录/VDDIC_Gamma_Demura/项目_IC.gamma\n\n" + 
                "3. 窗口1-8：\n" + 
                "    右侧8个窗口与Debug界面的列表1-8窗口联动\n\n"
                ,"使用说明： <Contact: Suzf>");
        }

        private void ShowFunctionGroup()
        {
            int i, j, FGNum, FG_BtnNum, FG_GroupBoxLoc;
            int FG_subBtnNum, FG_subXNum, FG_subYNum;
            string[] subPar;
            int btn_xsize, btn_xloc, btn_yloc;
            // Color Bccolor = Color.FromArgb(255, 0, 0, 0);
            // Color Frcolor = Color.Black;

            int nodeacount = 0;
            treeView_SideFunction.Nodes.Clear();
            for (i = 0; i < FGGroupBoxArry.Length; i++)
            {
                if (FGGroupBoxArry[i] != null) FGGroupBoxArry[i].Visible = false;
            }

            string InfPath = GTcfgPath;
            string temread = ReadIni("FuntionGroup", "FuntionGroupNum", InfPath);
            if (temread == "") return;
            FGNum = Convert.ToInt32(temread);
            GroupNum = FGNum;
            if (FGNum <= 0) return;
            FG_BtnNum = 0;
            FG_GroupBoxLoc = 0;
            FGGroupBoxArry = new GroupBox[FGNum];
            for (i = 0; i < FGNum; i++)
            {
                FGGroupBoxArry[i] = new GroupBox();

                temread = ReadIni("FuntionGroup_" + (i + 1).ToString(), "FG_Name", InfPath);
                FGGroupBoxArry[i].Text = temread;
                temread = ReadIni("FuntionGroup_" + (i + 1).ToString(), "FG_BtnNum", InfPath);
                if (temread != "")
                {
                    subPar = temread.Split(',');
                    FG_subBtnNum = Convert.ToInt32(subPar[0]);
                    FG_subXNum = Convert.ToInt32(subPar[2]);
                    FG_subYNum = Convert.ToInt32(subPar[1]);
                    Arr_BtnNum[i] = FG_subBtnNum;

                    if (FG_subBtnNum > 0)
                    {
                        btn_xsize = 650 / FG_subXNum;
                        TreeNode tempnode1 = new TreeNode(FGGroupBoxArry[i].Text);
                        tempnode1.Tag = "";
                        treeView_SideFunction.Nodes.Add(tempnode1);
                        nodeacount += 1;
                        for (j = 0; j < FG_subBtnNum; j++)
                        {

                            Function_Btn[FG_BtnNum] = new BtnType();
                            Function_Btn[FG_BtnNum].Btnname = ReadIni("FuntionGroup_" + (i + 1).ToString(), "FG_Btn" + (j + 1).ToString() + "_name", InfPath);
                            //temread = ReadIni("Demura", "Demura_Btn" + (i + 1) + "_code", InfPath).ToUpper();
                            Function_Btn[FG_BtnNum].BtnCode = ReadIni("FuntionGroup_" + (i + 1).ToString(), "FG_Btn" + (j + 1).ToString() + "_code", InfPath);

                            RadioArry[FG_BtnNum] = new RadioButton();
                            RadioArry[FG_BtnNum].Tag = FG_BtnNum;
                            btn_xloc = (j % FG_subXNum) * btn_xsize;
                            btn_yloc = j / FG_subXNum;
                            btn_yloc = 12 + btn_yloc * 33;
                            RadioArry[FG_BtnNum].Text = Function_Btn[FG_BtnNum].Btnname;
                            RadioArry[FG_BtnNum].Size = new System.Drawing.Size(btn_xsize - 4, 25);
                            //RadioArry[FG_BtnNum].Location = new System.Drawing.Point(20 + (j% FG_subXNum) * btn_xsize, );
                            RadioArry[FG_BtnNum].Location = new System.Drawing.Point(5 + btn_xloc, btn_yloc);
                            RadioArry[FG_BtnNum].BackColor = Color.LightGray;


                            FGGroupBoxArry[i].Controls.Add(RadioArry[FG_BtnNum]);
                            RadioArry[FG_BtnNum].Click += new System.EventHandler(this.RadioArry_Click); //统一的事件处理
                            RadioArry[FG_BtnNum].Visible = true;

                            //-------treeView_SideFunction
                            TreeNode tempnode2 = new TreeNode(Function_Btn[FG_BtnNum].Btnname);
                            tempnode2.Tag = Function_Btn[FG_BtnNum].BtnCode;
                            tempnode1.Nodes.Add(tempnode2);
                            nodeacount += 1;

                            FG_BtnNum += 1;

                        }

                    }
                    FGGroupBoxArry[i].Size = new System.Drawing.Size(650, FG_subYNum * 40);
                    FGGroupBoxArry[i].Location = new System.Drawing.Point(5, 65 + FG_GroupBoxLoc);
                    GourpBox_Function.Controls.Add(FGGroupBoxArry[i]);
                    FG_GroupBoxLoc += FG_subYNum * 42;
                }
            }



        }

        //显示控件end
        #endregion

        #region //串口发送接收code

        //ComReciveDataType ReciveData;
        //串口主动回读打开,修改触发方式为主动回读读
        private void SerialPort_ReadOpen()
        {

            Err_report = "SerialPort_ReadOpen";
            if (!frmHelp.comPort.IsOpen)
            {
                //try //在调用函数里捕获异常，子函数里mark 掉
                //{
                frmHelp.comPort.PortName = Detection.GetComNum();
                frmHelp.comPort.BaudRate = Setting.ComSet.comBaudRate;
                frmHelp.comPort.Open();

                frmHelp.comPort.DiscardInBuffer(); //清空缓冲区 
                frmHelp.statusStrip1.BackColor = Color.Green;
                frmHelp.toolStripStatusLabel_Tips.Text = "Open " + frmHelp.comPort.PortName + " " + frmHelp.comPort.BaudRate.ToString();

                frmHelp.comPort.ReceivedBytesThreshold = 4080;
                //}
                ////catch
                //{
                //    MessageBox.Show("没有搜索到串口！", "错误提示");
                //}
            }
            else
            {
                frmHelp.comPort.DiscardInBuffer(); //清空缓冲区 
                frmHelp.comPort.ReceivedBytesThreshold = 4080;
            }
        }

        //串口主动回读关闭,修改触发方式改为DataReceived 触发
        private void SerialPort_ReadClose()
        {
            try
            {
                frmHelp.comPort.ReceivedBytesThreshold = 1; //把触发方式修改回去
                                                            // frmHelp.comPort.DiscardInBuffer(); //清空缓冲区 
            }
            catch
            {
                MessageBox.Show("没有搜索到串口！", "错误提示");
            }
        }

        //串口主动回读侦测，每10ms 侦测一次，waitloopnum 为侦测等待次数，最大waittime=10*waitloopnum;
        private string SerialPort_Read(int waitloopnum, out int returnnum, out byte[] returnbuf) //read compart
        {
            //byte[] tembuf = new byte[1];
            returnbuf = new byte[1];
            int readnum = 0;
            // string returnstr = "";
            string Msgstr = "";
            try
            {
                do
                {   // call Application.ProcessMessage;
                    if (frmHelp.comPort.BytesToRead == 0)
                    {
                        waitloopnum -= 1;
                        //  label_RecMsg.Text += ".";
                        Thread.Sleep(10);
                        Application.DoEvents();
                    }
                    else
                    {
                        Thread.Sleep(10);
                        Application.DoEvents();
                        waitloopnum = 0;
                        readnum = frmHelp.comPort.BytesToRead;
                        returnbuf = new byte[readnum];
                        frmHelp.comPort.Read(returnbuf, 0, readnum);
                        Msgstr += returnbuf[0].ToString("X2");
                        for (int i = 1; i < readnum; i++)
                        {
                            Msgstr += " " + returnbuf[i].ToString("X2");
                        }
                        //returnstr += "\r\n";
                        //text_RecMsg.Text += Msgstr + "\r\n";
                        AddMsgShow(text_RecMsg, RecDebugflag, Msgstr);
                    }

                } while (waitloopnum > 0);


            }
            catch
            {
                MessageBox.Show("没有搜索到串口！", "错误提示");
            }
            returnnum = readnum;
            return Msgstr;
        }

        // ComportWrite from string to byte and write
        private void WriteComport(string sendstr)
        {
            int pack_num; byte temb;
            string orgstr;
            string[] strarray;
            orgstr = sendstr.Replace(",", " ");
            strarray = orgstr.Split(' ');
            pack_num = strarray.Length;
            Setting.TempRecord.cmdLen = pack_num + 3;
            Send_buf = new byte[pack_num + 3];
            //text_SendMsg.Text = text_SendMsg.Text + sendstr + "\r\n";
            if (pack_num >= 2)
            {
                for (int i = 0; i < pack_num; i++)
                {
                    temb = Convert.ToByte(strarray[i], 16);
                    Send_buf[i + 1] = Convert.ToByte(strarray[i], 16);
                }
                Send_buf[0] = Convert.ToByte(strarray[0], 16);

                if ((pack_num <= 250))
                {

                    Send_buf[1] = Convert.ToByte(strarray[1], 16);
                    Send_buf[2] = (byte)(pack_num - 2);
                }
                else if ((pack_num > 250) & (pack_num <= 360))
                {
                    Send_buf[1] = (byte)(Convert.ToByte(strarray[1], 16) | 0x40);
                    Send_buf[2] = (byte)(pack_num - 2 - 128);
                }
                else if ((pack_num > 360) & (pack_num <= 500))
                {
                    Send_buf[1] = (byte)(Convert.ToByte(strarray[1], 16) | 0x80);
                    Send_buf[2] = (byte)(pack_num - 2 - 128 * 2);
                }
                else
                {
                    Send_buf[1] = (byte)(Convert.ToByte(strarray[1], 16) | 0xC0);
                    Send_buf[2] = (byte)(pack_num - 2 - 128 * 3);
                }
                CRCData.CalculateCrc16(Send_buf, out Send_buf[pack_num + 1], out Send_buf[pack_num + 2]);
                if (SendDebugflag)
                {
                    orgstr = Send_buf[0].ToString("X2");
                    for (int i = 1; i < pack_num + 3; i++)
                    {
                        orgstr += " " + Send_buf[i].ToString("X2");
                    }
                    AddMsgShow(text_SendMsg, SendDebugflag, orgstr);
                }
                if (frmHelp.comPort.IsOpen)
                { //打开则直接发送
                    try
                    {
                        frmHelp.comPort.DiscardInBuffer(); //清空接受区数据
                        frmHelp.comPort.Write(Send_buf, 0, pack_num + 3);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                    }
                }
                else
                { //没打开则尝试打开然后发送
                    try
                    {
                        frmHelp.comPort.PortName = Detection.GetComNum();
                        frmHelp.comPort.BaudRate = Setting.ComSet.comBaudRate;
                        frmHelp.openSerialPort(true);
                        frmHelp.comPort.DiscardInBuffer(); //清空接受区数据
                        frmHelp.comPort.Write(Send_buf, 0, pack_num + 3);
                    }
                    catch
                    {
                        MessageBox.Show("没有搜索到串口！", "错误提示");
                    }
                }
            }
        }
        // ComportWrite from string to byte and write without packnum
        private void WriteComPortPackage(string sendstr)
        {
            byte pack_num; byte temb;
            string orgstr;
            string[] strarray;
            orgstr = sendstr.Replace(",", " ");
            strarray = orgstr.Split(' ');
            pack_num = (byte)strarray.Length;
            Setting.TempRecord.cmdLen = pack_num + 2;
            Send_buf = new byte[pack_num + 2];
            //text_SendMsg.Text = text_SendMsg.Text + sendstr + "\r\n";
            AddMsgShow(text_SendMsg, SendDebugflag, sendstr);
            if (pack_num >= 2)
            {
                for (int i = 0; i < pack_num; i++)
                {
                    temb = Convert.ToByte(strarray[i], 16);
                    Send_buf[i] = Convert.ToByte(strarray[i], 16);
                }
                //Send_buf[0] = Convert.ToByte(strarray[0], 16);
                //Send_buf[1] = Convert.ToByte(strarray[1], 16);
                //Send_buf[2] = (byte)(pack_num - 2);
                CRCData.CalculateCrc16(Send_buf, out Send_buf[pack_num], out Send_buf[pack_num + 1]);
                if (frmHelp.comPort.IsOpen)
                { //打开则直接发送
                    try
                    {
                        frmHelp.comPort.DiscardInBuffer(); //清空接受区数据
                        frmHelp.comPort.Write(Send_buf, 0, pack_num + 2);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                    }
                }
                else
                { //没打开则尝试打开然后发送
                    try
                    {
                        frmHelp.comPort.PortName = Detection.GetComNum();
                        frmHelp.comPort.BaudRate = Setting.ComSet.comBaudRate;
                        frmHelp.openSerialPort(true);

                        frmHelp.comPort.DiscardInBuffer(); //清空接受区数据
                        frmHelp.comPort.Write(Send_buf, 0, pack_num + 3);
                    }
                    catch
                    {
                        MessageBox.Show("没有搜索到串口！", "错误提示");
                    }
                }
            }
        }

        private void AddMsgShow(object Msgobj, bool showflag, string Msgstring)
        {
            if (showflag == true)
            {
                TextBox TextBoxTmp = (TextBox)Msgobj;
                TextBoxTmp.AppendText(Msgstring + "\r\n");
                // TextBoxTmp.Text += Msgstring + "\r\n";
                // TextBoxTmp.SelectionStart = TextBoxTmp.Text.Length;
                // TextBoxTmp.ScrollToCaret();//滚动到光标处
            }
        }
        private void AddScriptShow(object Msgobj, bool showflag, string Msgstring)
        {

            int temindex = Convert.ToInt32(text_script_send_all.Tag);
            if (temindex != 39)
            {
                ScriptSavestring[temindex] = text_script_send_all.Text;// 保存当前文本到string   text_scriptSend.Text = loadScriptFromfile(of.FileName);
                text_script_send_all.Tag = "39";
            }

            if (showflag == true)
            {
                TextBox TextBoxTmp = (TextBox)Msgobj;
                TextBoxTmp.Text = Msgstring + "\r\n";
                //TextBoxTmp.AppendText(Msgstring);
            }
        }
        private void T1_Tick(object sender, EventArgs e)
        {
            T1.Enabled = false;
            text_RecMsg.Text = text_RecMsg.Text + "通讯故障!\r\n";
            text_RecMsg.Focus();//获取焦点
            text_RecMsg.Select(text_RecMsg.TextLength, 0);//光标定位到文本最后
            text_RecMsg.ScrollToCaret();//滚动到光标处
        }
        //串口接收,此处为事件触发返回方式
        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            return;// 修改回读方式此处不响应，改为主动侦测读取
        }
        //RadioArry gamma group 选择触发处理

        // Radio 按钮发处理切换gamma page
        private void RadioArry_Click(object sender, System.EventArgs e)
        {
            // int array_id = Convert.ToInt16(((RadioButton)sender).Tag) + 1;//通过sender判断激发事件的控件
            //  GGourpBox.Tag = array_id;

            RadioButton btnTmp = (RadioButton)sender;
            Btn_id = Convert.ToInt16(btnTmp.Tag);
            // Btn_id = Btn_id >> 1;
            // string result = Write99Comport_muilt(IC_demura[Btn_id].BtnCode); //for ICNA3511  使用99端口
            Stopflag = false;
            IClosing = true; //关闭自动recivew
            SerialPort_ReadOpen();
            //string ss = Write99Comport_muilt(text_scriptSend.Text);

            //显示当前状态
            Label_Status_Display(sender, e);

            textBox_Function.Text = Function_Btn[Btn_id].BtnCode;
            string ss = Write99Comport_Script(Function_Btn[Btn_id].BtnCode);
            //text_SendMsg.Text += ss;

            //鼠标点击定义的.gamma文件生产的按钮，触发快捷键数据变更
            ShortKey_DataChange_Click(sender, e);
        }


        // RGB W/R 按钮触发处理
        private void BtnArry_Click(object sender, System.EventArgs e)
        {
            //MessageBox.Show(((Button)sender).Text + " was clicked !"); //通过sender判断激发事件的控件
            if (Lockedflag == true) { return; }//加锁，防止没有完成再次点击
            Lockedflag = true;
            int rgb_id = Convert.ToInt16(((Button)sender).Tag);
            rgb_id = rgb_id >> 1;
            int startid = 0, endid = 0;
            int k = 0;
            Button btnTmp = (Button)sender;
            Err_report = "";
            try
            {
                Stopflag = false;
                IClosing = true; //关闭自动recivew
                switch (btnTmp.Name)
                {

                    case "W_W":
                    case "R_W":
                    case "G_W":
                    case "B_W":
                        {
                            // Setting.TempRecord.CmdType = 0x10;       //HF_GenW_port 
                            SerialPort_ReadOpen();
                            Nodevalue2ParValue(3, 0, 0);
                            string getcode = GetWitercode(rgb_id, 0);
                            AddScriptShow(text_script_send_all, ScriptDebugflag, getcode);
                            getcode = TransCode(getcode, HF_GenW_port);
                            // getcode = TransCode(getcode, "96,20");
                            WriteComport(getcode);
                            //Write99Comport_Script(text_scriptSend.Text);

                        }
                        break;
                    case "W_R":
                    case "G_R":
                    case "B_R":
                    case "R_R":
                        {
                            SerialPort_ReadOpen();
                            if (rgb_id == 0)
                            {
                                startid = 0;
                                endid = 2;
                            }
                            else
                            {
                                startid = rgb_id - 1;
                                endid = rgb_id - 1;
                            }
                            for (int j = startid; j <= endid; j++)
                            {
                                for (int i = 0; i < Maxarry; i++)
                                {
                                    k = j * Maxarry + i;
                                    NumArry[k].ForeColor = Color.Red;
                                }
                            }
                            string getcode = GetReadcode(rgb_id);// 回读RGB 单色 ID
                            AddScriptShow(text_script_send_all, ScriptDebugflag, getcode);
                            ParValue2Nodevalue();
                            Err_report = " Convert.ToInt16(ICGT.MaxNodeValue);";
                            int Maxvalue = Convert.ToInt16(ICGT.MaxNodeValue.Replace("*", ""));
                            for (int j = startid; j <= endid; j++)
                            {
                                for (int i = 0; i < Maxarry; i++)
                                {
                                    k = j * Maxarry + i;
                                    if ((RGB_Value_A[j][i] >= 0) & (RGB_Value_A[j][i] <= Maxvalue))
                                    {
                                        NumArry[k].Value = RGB_Value_A[j][i];
                                        NumArry[k].ForeColor = Color.Black;
                                    }
                                }
                            }
                        }
                        break;
                    case "Calc_XYZ":
                        {
                            double setgammarate = Convert.ToDouble(text_gamaRate.Text);

                            GrMindata.SetLvxy(0.001, Convert.ToDouble(text_255targe_sx.Text), Convert.ToDouble(text_255targe_sy.Text));
                            GrMindata.R_index = GrMindata.G_index = GrMindata.B_index = 0;
                            //设定目标值
                            GrMaxTarget.SetLvxy(Convert.ToDouble(text_255targe_lv.Text), Convert.ToDouble(text_255targe_sx.Text), Convert.ToDouble(text_255targe_sy.Text));
                            GrMaxTarget.R_index = GrMaxTarget.G_index = GrMaxTarget.B_index = 255;
                            Cacla_Target(setgammarate, GrMindata, GrMaxTarget, 60);
                            for (int i = 0; i < 3; i++)
                            {
                                for (int j = 0; j < ICGT.NodeEffetNum; j++)
                                {
                                    TextArry[i, j].Text = Target_XYZ[i, j].ToString();
                                }
                            }
                        }
                        break;
                    case "Enter_GammaMode":
                        {
                            BtnArry[9].Name = "Exit_GammaMode"; //重新命名
                            BtnArry[9].Text = "Exit_GammaMode";
                            Stopflag = false;
                            IClosing = true; //关闭自动recivew
                            SerialPort_ReadOpen();
                            string ss = Write99Comport_Script(ICGT.EnterGammaMode_Code);
                        }
                        break;
                    case "Exit_GammaMode":
                        {
                            BtnArry[9].Name = "Enter_GammaMode";
                            BtnArry[9].Text = "Enter_GammaMode";
                            Stopflag = false;
                            IClosing = true; //关闭自动recivew
                            SerialPort_ReadOpen();
                            string ss = Write99Comport_Script(ICGT.ExitGammaMode_Code);

                        }
                        break;
                    default:
                        break;
                }

                SerialPort_ReadClose();
            }
            catch (Exception emsg)
            {
                if (MessageBox.Show(Err_report + "\r\n" + emsg.Message + "\r\n continue run?", "Error Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    Stopflag = true;
                    goto Err_End;
                }
                // MessageBox.Show(emsg.Message, "系统提示：");
            }

        Err_End:
            Lockedflag = false;
            return;
        }

        //Btn_fun_Arry_Click
        private void Btn_fun_Arry_Click(object sender, System.EventArgs e)
        {
            Button btnTmp = (Button)sender;
            int Btn_id = Convert.ToInt16(btnTmp.Tag);
            // Btn_id = Btn_id >> 1;
            string result = Write99Comport_muilt(IC_demura[Btn_id].BtnCode); //for ICNA3511  使用99端口
            T1.Enabled = false;
            T1.Interval = 50;
            T1.Enabled = true;

        }
        private void treeView_SideFunction_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //  int result = GenDemura_fromfile("02", "540", "2C", "3C", FileName);
            if (treeView_SideFunction.SelectedNode == null) //是父node 
                return;

            int nodeindex = treeView_SideFunction.SelectedNode.Index;
            string nodetag = treeView_SideFunction.SelectedNode.Tag.ToString();
            try
            {
                Stopflag = false;
                IClosing = true; //关闭自动recivew
                SerialPort_ReadOpen();
                //string ss = Write99Comport_muilt(text_scriptSend.Text);
                string ss = Write99Comport_Script(nodetag);
                //text_SendMsg.Text += ss;
            }
            catch (Exception emsg)
            {
                SerialPort_ReadClose();
                if (MessageBox.Show(Err_report + "\r\n" + emsg.Message + "\r\n continue run?", "Error Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    Stopflag = true;
                    goto Err_End;
                }
                // MessageBox.Show(emsg.Message, "系统提示：");
            }

            SerialPort_ReadClose();

        Err_End:
            return;
        }

        #endregion

        #region  //参数相互转化code

        // 将10bit node 参数转化为8bit寄存器参数
        private void Nodevalue2ParValue(int datatranflag, int orgindex, int followindex) //强制followowindex value= orgindex value, 不用设定为0,0
        {

            Err_report = "Nodevalue2ParValue";
            int k = 0;
            //  int[] nodeCorrectresult;
            //   nodeCorrectresult = new int[ICGT.NodeNum];
            //datatranflag if true=自动先从Numeerr 控件 update,if false=  不从控件更新
            /*把控件值更新到数组 datatranflag=0 不更新，
                                       Bit0=0x01只NumArr-->RGB_value,
                                       Bit1=0x02 NumArry-->Ref value,
                                       Bit2=0x04 RGB_value-->ref,
                                       Bit3=0x08 RGB_value->NumArry                                       
                                       Bit4=0x10 ref-> RGB_value                                     
                                       Bit5=0x20 RGB_value =0 all RGB clear                                                                     
                                       Bit6=0x40 ref orgindex -> RGB_value  followindex                                               
                                       Bit7=0x80 RGB_value orgindex -> ref  followindex
                                       */
            if (datatranflag > 0)
            {
                for (int i = 0; i < 3; i++)
                {
                    if ((datatranflag & 0x3F) > 0)
                    {
                        for (int j = 0; j < ICGT.NodeNum; j++)
                        {
                            k = i * Maxarry + j;
                            if ((datatranflag & 0x01) > 0) RGB_Value_A[i][j] = (Int16)NumArry[k].Value;
                            if ((datatranflag & 0x02) > 0) RGB_RefValue_A[i][j] = (Int16)NumArry[k].Value;
                            if ((datatranflag & 0x04) > 0) RGB_RefValue_A[i][j] = RGB_Value_A[i][j];
                            if ((datatranflag & 0x08) > 0) NumArry[k].Value = RGB_Value_A[i][j];
                            if ((datatranflag & 0x10) > 0) RGB_Value_A[i][j] = RGB_RefValue_A[i][j];
                            if ((datatranflag & 0x20) > 0) RGB_Value_A[i][j] = 0;
                        }
                    }
                    if ((datatranflag & 0x40) > 0) RGB_Value_A[i][followindex] = RGB_RefValue_A[i][orgindex];
                    if ((datatranflag & 0x80) > 0) RGB_RefValue_A[i][followindex] = RGB_Value_A[i][orgindex];

                }
            }

            if (ICGT.NodeCorrect != "")// cfg 有node follow 设定在则更新
            {
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < ICGT.NodeNum; j++)
                    {
                        k = ICGT.NodeFollow_A[j];//NodeFollow_A 内 存储着 index 重新maping 关系，在cfg 时生成
                        RGB_Value_A[i][j] = RGB_Value_A[i][k];//nodevalue 重新定向
                    }
                }
            }
            if (ICGT.ParBitmap == "MS")
            {
                if (ICGT.NodeMuxPar == "1-1") //1个参数对应1个值，一一对应
                {
                    for (int i = 0; i < 3; i++)
                    {         //RGB_Value_A[i][followindex] = RGB_Value_A[i][orgindex];
                        for (int j = 0; j < ICGT.NodeNum; j++)
                        {
                            k = i * Maxarry + j;
                            RGB_ParValue_A[i][j] = (byte)(RGB_Value_A[i][j] & 255);
                        }
                    }
                }
                if (ICGT.NodeMuxPar == "1-2")//nova ,rayduim家IC 属于此类,
                {
                    for (int i = 0; i < 3; i++)
                    {
                        // RGB_Value_A[i][followindex] = RGB_Value_A[i][orgindex];
                        for (int j = 0; j < ICGT.NodeNum; j++)
                        {
                            k = i * Maxarry + j;
                            RGB_ParValue_A[i][j * 2] = (byte)(RGB_Value_A[i][j] >> 8);
                            RGB_ParValue_A[i][j * 2 + 1] = (byte)(RGB_Value_A[i][j] & 255);
                        }
                    }
                }
                else if (ICGT.NodeMuxPar == "2-3-C") // chipone 家IC
                {
                    for (int i = 0; i < 3; i++)
                    {
                        // RGB_Value_A[i][followindex] = RGB_Value_A[i][orgindex];
                        for (int j = 0; j < ICGT.NodeNum / 2; j++)
                        {
                            RGB_ParValue_A[i][j * 3] = (byte)(((RGB_Value_A[i][j * 2] >> 8) << 4) + (RGB_Value_A[i][j * 2 + 1] >> 8));
                            RGB_ParValue_A[i][j * 3 + 1] = (byte)(RGB_Value_A[i][j * 2] & 255);
                            RGB_ParValue_A[i][j * 3 + 2] = (byte)(RGB_Value_A[i][j * 2 + 1] & 255);
                        }
                    }
                }
                else if (ICGT.NodeMuxPar == "2-3-S") // synatics 家IC
                {
                    for (int i = 0; i < 3; i++) //nouser 
                    {
                        // RGB_Value_A[i][followindex] = RGB_Value_A[i][orgindex];
                        if (i == 1)
                        {
                            for (int j = 1; j < ICGT.NodeNum / 2; j++)
                            {
                                RGB_ParValue_A[i][j * 3 - 1] = (byte)(RGB_Value_A[i][j * 2 - 1] >> 4);
                                RGB_ParValue_A[i][j * 3] = (byte)(((RGB_Value_A[i][j * 2 - 1] & 0x0F) << 4) + (RGB_Value_A[i][j * 2] >> 8));
                                RGB_ParValue_A[i][j * 3 + 1] = (byte)(RGB_Value_A[i][j * 2] & 255);
                            }
                            RGB_ParValue_A[i][0] = (byte)(((RGB_Value_A[i - 1][ICGT.NodeNum - 1] & 0x0F) << 4) + (RGB_Value_A[i][0] >> 8));
                            RGB_ParValue_A[i][1] = (byte)(RGB_Value_A[i][0] & 255);
                        }
                        else
                        {
                            for (int j = 0; j < ICGT.NodeNum / 2; j++)
                            {
                                RGB_ParValue_A[i][j * 3] = (byte)(RGB_Value_A[i][j * 2] >> 4);
                                RGB_ParValue_A[i][j * 3 + 1] = (byte)(((RGB_Value_A[i][j * 2] & 0x0F) << 4) + (RGB_Value_A[i][j * 2 + 1] >> 8));
                                RGB_ParValue_A[i][j * 3 + 2] = (byte)(RGB_Value_A[i][j * 2 + 1] & 255);
                            }
                        }

                    }

                }
            }

            if (ICGT.ParBitmap == "LS")
            {
                for (int i = 0; i < 3; i++)
                {
                    // RGB_Value_A[i][followindex] = RGB_Value_A[i][orgindex];
                    for (int j = 0; j < ICGT.NodeNum; j++)
                    {
                        RGB_ParValue_A[i][j * 2 + 1] = (byte)(RGB_Value_A[i][j] >> 8);
                        RGB_ParValue_A[i][j * 2] = (byte)(RGB_Value_A[i][j] & 255);
                    }
                }
            }
        }

        // 当调节第endindex node,0~endindex-1 node 值按照n node 值缩放
        private void NodevalueZoom(int startindex, int endindex) //强制followowindex value= orgindex value, 不用设定为0,0
        {
            double zoomrate;
            if (NodePos_A[endindex] > 0)
            {
                for (int i = 0; i < 3; i++)
                {
                    zoomrate = RGB_Value_A[i][endindex];
                    zoomrate = RGB_Value_A[i][endindex] / NodePos_A[endindex];
                    for (int j = startindex; j < endindex; j++)
                    {
                        RGB_Value_A[i][j] = (Int16)(NodePos_A[j] * zoomrate);
                    }
                }
            }

        }

        // 将8bit寄存器参数转化为10bit/12bit node value参数
        private void ParValue2Nodevalue()  //for code to value and   read register user
        {
            int k = 0;
            Int16 Msvalue, Lsvalue, Temp;
            Err_report = "ParValue2Nodevalue";
            if (ICGT.ParBitmap == "MS")
            {
                if (ICGT.NodeMuxPar == "1-2")
                {
                    for (int i = 0; i < 3; i++)
                    {
                        for (int j = 0; j < ICGT.NodeNum; j++)
                        {
                            k = i * Maxarry + j;
                            Msvalue = (Int16)(RGB_ParValue_A[i][j * 2] << 8);
                            Lsvalue = RGB_ParValue_A[i][j * 2 + 1];
                            Temp = (Int16)(Msvalue + Lsvalue);
                            RGB_Value_A[i][j] = Temp;
                            //NumArry[k].Text = Temp.ToString();
                        }
                    }
                }
                else if (ICGT.NodeMuxPar == "2-3-C")// chipone 家IC
                {
                    for (int i = 0; i < 3; i++)
                    {
                        for (int j = 0; j < ICGT.NodeNum / 2; j++)
                        {
                            k = i * Maxarry + j;
                            Msvalue = (Int16)((RGB_ParValue_A[i][j * 3] * 0xF0) << 4);
                            Lsvalue = RGB_ParValue_A[i][j * 3 + 1];
                            Temp = (Int16)(Msvalue + Lsvalue);
                            RGB_Value_A[i][j * 2] = Temp;

                            Msvalue = (Int16)((RGB_ParValue_A[i][j * 3] * 0x0F) << 8);
                            Lsvalue = RGB_ParValue_A[i][j * 3 + 2];
                            Temp = (Int16)(Msvalue + Lsvalue);
                            RGB_Value_A[i][j * 2 + 1] = Temp;
                        }
                    }
                }
                else if (ICGT.NodeMuxPar == "2-3-S")// synatics 家IC
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (i == 1)//green 中间
                        {
                            for (int j = 0; j < ICGT.NodeNum / 2; j++)
                            {
                                k = i * Maxarry + j;
                                Msvalue = (Int16)((RGB_ParValue_A[i][j * 3] & 0xFF) << 4);
                                Lsvalue = (Int16)((RGB_ParValue_A[i][j * 3 + 1] & 0xF0) >> 4);
                                Temp = (Int16)(Msvalue + Lsvalue);
                                RGB_Value_A[i][j * 2] = Temp;

                                Msvalue = (Int16)((RGB_ParValue_A[i][j * 3] * 0x0F) << 8);
                                Lsvalue = RGB_ParValue_A[i][j * 3 + 2];
                                Temp = (Int16)(Msvalue + Lsvalue);
                                RGB_Value_A[i][j * 2 + 1] = Temp;
                            }
                        }
                        else
                        {
                            for (int j = 0; j < ICGT.NodeNum / 2; j++)
                            {
                                k = i * Maxarry + j;
                                Msvalue = (Int16)((RGB_ParValue_A[i][j * 3] & 0xFF) << 4);
                                Lsvalue = (Int16)((RGB_ParValue_A[i][j * 3 + 1] & 0xF0) >> 4);
                                Temp = (Int16)(Msvalue + Lsvalue);
                                RGB_Value_A[i][j * 2] = Temp;

                                Msvalue = (Int16)((RGB_ParValue_A[i][j * 3] * 0x0F) << 8);
                                Lsvalue = RGB_ParValue_A[i][j * 3 + 2];
                                Temp = (Int16)(Msvalue + Lsvalue);
                                RGB_Value_A[i][j * 2 + 1] = Temp;
                            }
                        }
                    }
                }
            }
            if (ICGT.ParBitmap == "LS")
            {
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < ICGT.NodeNum; j++)
                    {
                        k = i * Maxarry + j;
                        Msvalue = (Int16)(RGB_ParValue_A[i][j * 2 + 1] << 8);
                        Lsvalue = RGB_ParValue_A[i][j * 2];
                        Temp = (Int16)(Msvalue + Lsvalue);
                        RGB_Value_A[i][j] = Temp;
                        //NumArry[k].Text = Temp.ToString();
                    }
                }
            }
        }

        //form for getcode  write register user
        private string GetWitercode(int rgb_selc, int NodeOmitNum) //string to byte[]
        {
            StringBuilder code_out = new StringBuilder("");
            int Rindex, Pindex;
            int parcount = 0;
            int offsetindex = rgb_selc * Maxarry;
            int rgb_indexstart = 0, rgb_indexend = 0;
            int ParOmitNum = 0;

            Err_report = "GetWitercode";
            if ((NodeOmitNum == ICGT.NodeEffetNum) || (NodeOmitNum == 0)) //待完善用于，后面截取
            { ParOmitNum = ICGT.ParNum; }
            else if (ICGT.NodeMuxPar == "1-2")
            { ParOmitNum = NodeOmitNum * 2; }
            else if (ICGT.NodeMuxPar == "2-3")
            { ParOmitNum = (NodeOmitNum / 2 + NodeOmitNum % 2) * 3; }

            if (rgb_selc == 0)
            {
                rgb_indexstart = 0;
                rgb_indexend = 2;
            }
            else
            {
                rgb_indexstart = rgb_selc - 1;
                rgb_indexend = rgb_selc - 1;
                //if ((rgb_selc & 3)) == 1) { }
            }

            if (ICGT.RegType == "SHORT") //for 1CMD+1par IC
            {
                code_out.Append("DSIW_1P_S;"); //for ryduim IC 1reg+1par 开始 区域内使用96 06 接口改为1个封包下发
                for (int k = rgb_indexstart; k <= rgb_indexend; k++)
                {
                    if (ICGT.RGB_PageReg[k] != "") code_out.Append("DSIW " + ICGT.RGB_PageReg[k]); //code_out.Append("\r\n");
                    for (int i = 0; i < ICGT.ParNum; i++)
                    {
                        //code_out.Append("DSIW " + RGB_Reg_A[rgb_selc][i].ToString("X2"));
                        code_out.Append("DSIW " + RGB_Reg_A[k][i] + "," + RGB_ParValue_A[k][i].ToString("X2") + ";");
                    }
                }
                code_out.Append("DSIW_1P_E;"); //for ryduim IC 1reg+1par 开始  
            }
            if (ICGT.RegType == "LONG") //for 1CMD+1par+2par=3Par+... IC //for synaptic IC
            {
                code_out.Append(ICGT.RGB_PageReg[rgb_selc]); //code_out.Append("\r\n");
                for (int i = 0; i < ICGT.ParNum; i++)
                {   //code_out.Append(RGB_Reg_A[rgb_selc][i].ToString("X2"));
                    code_out.Append(RGB_ParValue_A[rgb_selc][i].ToString("X2"));
                    code_out.Append(",");
                }
                code_out.Append("\r\n");
            }
            if (ICGT.RegType == "MIX") //for  CMD1+1par+2par+3Par+... and CMD2+ 7PAr +8PAR IC
            {
                // int test, rgb_index;
                int[] temindex = new int[3];

                for (int k = rgb_indexstart; k <= rgb_indexend; k++)
                {
                    for (int i = 0; i < ICGT.ParNum; i++)
                    {
                        Rindex = RGB_RegIndex_A[k][i] + k * ICGT.RegNum;
                        Pindex = RGB_ParIndex_A[k][i];
                        // test = RGB_RegLWrite_A[Rindex][Pindex];
                        //  test = RGB_ParValue_A[rgb_selc][i];
                        RGB_RegLWrite_A[Rindex][Pindex] = RGB_ParValue_A[k][i];

                    }
                    parcount = 0;

                    if (ICGT.RGB_PageReg[k] != "") code_out.Append(ICGT.RGB_PageReg[k]);
                    for (int i = 0; i < ICGT.RegNum; i++)
                    {
                        if (parcount < ParOmitNum)
                        {
                            //parcount = parcount + 1;
                            code_out.Append("DSIW " + RGB_Reg_A[k][i]);
                            Pindex = RGB_Reg_Leght_A[k][i];
                            for (int j = 0; j < Pindex; j++)
                            {
                                code_out.Append(" ");
                                code_out.Append(RGB_RegLWrite_A[k * ICGT.RegNum + i][j].ToString("X2"));
                            }
                            code_out.Append("\r\n");
                        }
                    }
                }

            }
            string temstr = code_out.ToString();
            temstr = temstr.Replace(";", "\r\n");
            temstr = temstr.Replace(",", " ");
            //return code_out.ToString().Replace(";", "\r\n");
            return temstr;
        }
        //为读取做准备
        private string GetReadcode(int rgb_selc) //string to byte[]
        {
            StringBuilder code_out = new StringBuilder("");
            int accountnum = 0, Readnum;
            int offsetindex = rgb_selc * Maxarry;
            int rgb_indexstart = 0, rgb_indexend = 0;
            // byte tembytetest = 0;
            string sendtemstr = "", regstring = "", parstring = "";

            Err_report = "GetReadcode";
            int num;
            if (rgb_selc == 0)
            {
                rgb_indexstart = 0;
                rgb_indexend = 2;
            }
            else
            {
                rgb_indexstart = rgb_selc - 1;
                rgb_indexend = rgb_selc - 1;
                //if ((rgb_selc & 3)) == 1) { }
            }

            if (ICGT.RegType == "SHORT") //for 1CMD+1par IC
            {
                for (int k = rgb_indexstart; k <= rgb_indexend; k++)
                {
                    Readnum = ICGT.RegNum;
                    accountnum = 0;
                    sendtemstr = "DSIR_1P_S;"; //for ryduim IC 1reg+1par 开始 区域内使用96 16 接口改为1个封包下发回读
                    for (int i = 0; i < ICGT.RegNum; i++)
                    { sendtemstr += "DSIR " + RGB_Reg_A[k][i] + "," + RGB_ParValue_A[k][i].ToString("X2") + ";"; }
                    sendtemstr += "DSIR_1P_E;";
                    regstring = TransCode(sendtemstr, "96,16");

                    WriteComport(regstring);
                    sendtemstr = SerialPort_Read(Readnum * 2, out num, out readbuff);
                    if (num > 4)
                    {
                        regstring = "DSIR_1P_Reg";
                        parstring = "DSIR_1P_Par";
                        //regstring = sendtemstr.Substring(12, (num - 6) * 3 - 1);
                        for (int j = 0; j < Readnum; j++)
                        {
                            //tembytetest=readbuff[j + 4];
                            RGB_ParValue_A[k][accountnum] = readbuff[j * 2 + 4];
                            regstring += " " + readbuff[j * 2 + 3].ToString("X2");
                            parstring += " " + readbuff[j * 2 + 4].ToString("X2");
                            accountnum += 1;
                        }
                        AddMsgShow(text_scriptRec, ScriptDebugflag, regstring);
                        AddMsgShow(text_scriptRec, ScriptDebugflag, parstring);
                        code_out.Append(parstring + "\r\n");
                    }

                }

            }
            if (ICGT.RegType == "LONG") //for 1CMD+1par+2par=3Par+... IC
            {
                code_out.Append(ICGT.RGB_PageReg[0]);
                code_out.Append(" ");
                code_out.Append(ICGT.ParNum.ToString("X2")); //read ParNum 个参数
                code_out.Append("\r\n");
            }
            if (ICGT.RegType == "MIX") //for  CMD1+1par+2par+3Par+... and CMD2+ 7PAr +8PAR IC
            {
                int[] temindex = new int[3];
                for (int k = rgb_indexstart; k <= rgb_indexend; k++)
                {
                    accountnum = 0;
                    for (int i = 0; i < ICGT.RegNum; i++)
                    {
                        Readnum = RGB_Reg_Leght_A[k][i];
                        sendtemstr = "99,26," + RGB_Reg_A[k][i] + "," + Readnum.ToString("x2");//[1]=register
                        for (int j = 1; j < Readnum; j++)
                        {
                            sendtemstr = sendtemstr + ",00";
                        }
                        Delay(1);
                        WriteComport(sendtemstr);
                        sendtemstr = SerialPort_Read(Readnum * 15, out num, out readbuff);
                        if (num > 4)
                        {
                            regstring = sendtemstr.Substring(12, (num - 6) * 3 - 1);
                            AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIR " + RGB_Reg_A[k][i] + "=" + regstring);
                            for (int j = 0; j < Readnum; j++)
                            {
                                //tembytetest=readbuff[j + 4];
                                RGB_ParValue_A[k][accountnum] = readbuff[j + 4];
                                accountnum += 1;
                            }
                            code_out.Append("\r\n");
                        }
                    }
                }
            }
            string temstr = code_out.ToString();
            temstr = temstr.Replace(";", "\r\n");
            temstr = temstr.Replace(",", " ");
            //return code_out.ToString().Replace(";", "\r\n");
            return temstr;
        }


        // 去掉DSIW 改为 6A 端口
        private string TransCode(string inputstr, string GenW_port) //string to byte[]
        {
            StringBuilder code_out = new StringBuilder("");
            int packnum = 0;
            int Readnum = 0;//subnum = 0;
            string temstr = inputstr;
            string[] StrArry;
            string[] SubStrArry;
            temstr = temstr.Replace("\t", " ");
            temstr = temstr.Replace(",", " ");
            temstr = temstr.Replace("\r\n", ";");
            StrArry = temstr.Split(';');  //; 分行

            if ((StrArry[0] == "DSIW_1P_S") & (FasteWflag))
            {
                code_out.Append("96 06");
                for (int i = 1; i < StrArry.Length; i++)
                {
                    SubStrArry = StrArry[i].Split(' ');// 空格分字节  
                    if (SubStrArry[0] == "DSIW")
                    {
                        code_out.Append(" " + SubStrArry[1] + " " + SubStrArry[2]);
                    }
                }
                return code_out.ToString();
            }
            if ((StrArry[0] == "DSIR_1P_S") & (FasteWflag))
            {
                code_out.Append("96 16");
                for (int i = 1; i < StrArry.Length; i++)
                {
                    SubStrArry = StrArry[i].Split(' ');// 空格分字节  
                    if (SubStrArry[0] == "DSIR")
                    {
                        code_out.Append(" " + SubStrArry[1] + " " + SubStrArry[2]);
                    }
                }
                return code_out.ToString();
            }

            // code_out.Append("6A 20");
            for (int i = 0; i < StrArry.Length; i++)
            {
                if (StrArry[i].Length > 2)
                {
                    SubStrArry = StrArry[i].Split(' ');// 空格分字节                    
                    switch (SubStrArry[0].ToUpper())
                    {
                        case "DSIW":
                            {
                                //subnum = SubStrArry.Length + 1;
                                temstr = " " + SubStrArry.Length.ToString("X2") + " 04";
                                for (int j = 1; j < SubStrArry.Length; j++)
                                {
                                    temstr = temstr + " " + SubStrArry[j];
                                }
                                packnum = packnum + SubStrArry.Length;
                                code_out.Append(temstr);
                            }
                            break;
                        case "DSIR":
                            {
                                temstr = " " + SubStrArry.Length.ToString("X2") + " 14";
                                for (int j = 1; j < SubStrArry.Length; j++)
                                {
                                    temstr = temstr + " " + SubStrArry[j];
                                }
                                packnum = packnum + SubStrArry.Length;
                                code_out.Append(temstr);
                            }
                            break;
                        case "DSIRN":
                            {
                                Readnum = Convert.ToByte(SubStrArry[1], 16) + 1;
                                temstr = " " + Readnum.ToString("X2") + " 14";
                                for (int j = 1; j < Readnum; j++)
                                {
                                    temstr = temstr + " 00";
                                }
                                packnum = packnum + Readnum;
                                code_out.Append(temstr);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            // temstr = "6A 20";
            // temstr = "96 20"; //2KS  96端口

            code_out.Insert(0, GenW_port);
            return code_out.ToString();
            // return temstr;
        }

        private string GetWitercode_ICNA3511_15point(int inrgb_selc) // ICNA3511 15点专用
        {
            StringBuilder code_out = new StringBuilder("");
            int Rindex, Pindex;
            int offsetindex = inrgb_selc * Maxarry;
            //code_out.Append("DSIW FE,01,00,00,00;");

            code_out.Append(ICGT.GGN_StartCode);

            int test;
            if (ICGT.RegType == "MIX") //for 1CMD+1par+2par=3Par+... IC
            {
                for (int rgb_selc = 0; rgb_selc < 3; rgb_selc++)
                {
                    //RGB_ParValue_A[rgb_selc][15] = RGB_ParValue_A[rgb_selc][14];

                    for (int i = 0; i < ICGT.ParNum; i++)
                    {
                        Rindex = RGB_RegIndex_A[rgb_selc][i] + rgb_selc * ICGT.RegNum;
                        Pindex = RGB_ParIndex_A[rgb_selc][i];
                        test = RGB_RegLWrite_A[Rindex][Pindex];
                        test = RGB_ParValue_A[rgb_selc][i];
                        RGB_RegLWrite_A[Rindex][Pindex] = RGB_ParValue_A[rgb_selc][i];
                    }
                    for (int i = 0; i < ICGT.RegNum; i++)
                    {
                        code_out.Append("DSIW " + RGB_Reg_A[rgb_selc][i]);
                        Pindex = RGB_Reg_Leght_A[rgb_selc][i];
                        for (int j = 0; j < Pindex; j++)
                        {
                            code_out.Append(" ");
                            code_out.Append(RGB_RegLWrite_A[rgb_selc * ICGT.RegNum + i][j].ToString("X2"));

                        }
                        code_out.Append(";");
                    }
                }
            }

            //code_out.Append("DSIW FF,01;");

            code_out.Append(ICGT.GGN_EndCode);
            string temstr = code_out.ToString();
            temstr = temstr.Replace(";", "\r\n");
            temstr = temstr.Replace(",", " ");
            //return code_out.ToString().Replace(";", "\r\n");
            return temstr;
        }

        byte[] readbuff;
        int[] Ndec = new int[255];
        int[] Nhex = new int[255];
        string[] Msgbuff;
        //使用下位机99 口实现读写操作,多行输入 去掉DSIW 改为 99 00
        private string Write99Comport_muilt(string inputstr) //string to byte[] 使用 99 接口并 下发通讯
        {
            StringBuilder code_out = new StringBuilder("");
            int packnum = 0;
            int Readnum = 0;//subnum = 0;
            string temstr = inputstr;
            string[] StrArry;
            string[] SubStrArry;
            temstr = temstr.Replace(",", " ");
            temstr = temstr.Replace("\r\n", ";");
            StrArry = temstr.Split(';');  //; 分行

            // code_out.Append("6A 20");
            for (int i = 0; i < StrArry.Length; i++)
            {
                if (StrArry[i].Length > 4) //字符串长度大于4 DSIW 20
                {
                    SubStrArry = StrArry[i].Split(' ');// 空格分字节    
                    Application.DoEvents();
                    switch (SubStrArry[0].ToUpper())
                    {
                        case "DSIW":
                            {
                                temstr = "99" + " " + "1E";//LP_DCS_Long_Write [0],[1]
                                                           //subnum = SubStrArry.Length + 1;
                                                           //temstr = temstr + " " + SubStrArry.Length.ToString("X2") ; //no need calc num ,comwrite calc
                                for (int j = 1; j < SubStrArry.Length; j++)
                                {
                                    temstr = temstr + " " + SubStrArry[j];
                                }
                                //packnum = packnum + SubStrArry.Length;
                                code_out.Append(temstr);
                                WriteComport(temstr);

                                Thread.Sleep(20);
                            }
                            break;
                        case "DSIR":
                            {
                                temstr = " " + SubStrArry.Length.ToString("X2") + " 14";
                                for (int j = 1; j < SubStrArry.Length; j++)
                                {
                                    temstr = temstr + " " + SubStrArry[j];
                                }
                                packnum = packnum + SubStrArry.Length;
                                code_out.Append(temstr);
                            }
                            break;
                        case "DSIRN":
                            {
                                Readnum = Convert.ToByte(SubStrArry[1], 16) + 1;
                                temstr = " " + Readnum.ToString("X2") + " 14";
                                for (int j = 1; j < Readnum; j++)
                                {
                                    temstr = temstr + " 00";
                                }
                                packnum = packnum + Readnum;
                                code_out.Append(temstr);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            //temstr = "6A 20 " + packnum.ToString("X2");

            temstr = "99 90 00 00";
            WriteComport(temstr);
            code_out.Insert(0, temstr);
            code_out.Append("\r\n");
            return code_out.ToString();
            // return temstr;
        }

        //使用下位机6A,or 99 口实现读写操作,支持脚本  
        private string Write6AComport_Script(string inputstr, string GenW_port) //string to byte[] 使用 99 接口并 下发通讯
        {

            string get6Acode = TransCode(inputstr, GenW_port);
            WriteComport(get6Acode);
            int num;
            string read6Acode = SerialPort_Read(100 * 15, out num, out readbuff);
            return get6Acode;
        }

        //使用下位机99 口实现读写操作,支持脚本  
        private string Write99Comport_Script(string inputstr) //string to byte[] 使用 99 接口并 下发通讯
        {

            Err_report = "Write99Comport_Script";
            StringBuilder code_out = new StringBuilder("");
            int packnum = 0;
            int Readnum = 0;//subnum = 0;
            Msgbuff = new string[80];
            int[] loopnum = new int[10]; //记录每层loop的循环次数,最大支持10层循环
            int[] looploc = new int[10];//记录每层loop的code line位置
            int markloc = 0;
            string[] StrArry;
            string[] SubStrArry;
            string FirstSubstr;
            string ONLYW_RegString = ""; int Writemode = 1; //定义是否为智能回读对比代码功能
            int num, mathvalue;
            int Tem_delay = Convert.ToInt32(text_delaytime.Text);
            string readstring, compstring = "", regstring = "";
            string subtemstr = "";
            string sendtemstr = "", temstr = "";
            string inputtemstr = inputstr;

            inputtemstr = inputtemstr.Replace("\t", " ");
            inputtemstr = inputtemstr.Replace(" ", " ");
            inputtemstr = inputtemstr.Replace(",", " ");
            inputtemstr = inputtemstr.Replace(" ", "  ");
            //string pattern = "\\s+"; //正则变换pattern /\s+/g

            string pattern = " +";
            string replacement = " "; //空格
            Regex rgx = new Regex(pattern);

            inputtemstr = inputtemstr.Replace("\r\n", ";");
            StrArry = inputtemstr.Split(';');  //; 分行

            // code_out.Append("6A 20");
            for (int i = 0; i < StrArry.Length; i++)
            {
                Err_report = "Line:" + i.ToString() + ",code=" + StrArry[i];
                subtemstr = StrArry[i];
                subtemstr = rgx.Replace(subtemstr, replacement);  //利用正则变换去掉多余空格
                markloc = subtemstr.IndexOf("//");                   //查找是否含有//标记
                if (markloc >= 0) subtemstr = (subtemstr.Substring(0, markloc)).Trim();
                if (Stopflag == true) return "";
                if (subtemstr.Length < 2) continue; //字符串长度大于2 且stopflag 没有停止
                //=======针对Ryduim 格式替换处理===============================================[FE]-50
                if ((subtemstr.Length > 3) && (subtemstr.Substring(0, 1) == "[") && (subtemstr.Substring(3, 1) == "]"))
                {
                    subtemstr = subtemstr.Replace("[", "").Replace("]", "").Replace("-", " ").Replace(",", " ").Replace("=", " ");
                }
                SubStrArry = subtemstr.Trim().Split(' ');// 空格分字节    
                Application.DoEvents();
                FirstSubstr = SubStrArry[0].ToUpper();
                temstr = "";
                //=======兼容2K 原格式只有单纯inital code
                if ((FirstSubstr.Length == 2) && FirstSubstr != "IC")//======================================================2K 原格式只有单纯inital code
                {
                    if (ONLYW_RegString != "")
                    {
                        Writemode = 0;
                        if (ONLYW_RegString.IndexOf(FirstSubstr) > 0) Writemode = 1; //在只写列表找到寄存器则，写模式
                    }
                    if (Writemode == 1)// 默认自动识别为写指令
                    {
                        temstr = "99" + " " + "1E";//LP_DCS_Long_Write [0],[1]
                        for (int j = 0; j < SubStrArry.Length; j++)
                        {
                            if (SubStrArry[j].Length > 0)
                                temstr = temstr + " " + SubStrArry[j];
                        }
                        code_out.Append(temstr);
                        WriteComport(temstr);
                        Thread.Sleep(5);
                        AddMsgShow(text_scriptRec, ScriptDebugflag, subtemstr);
                    }
                    else //回读对比寄存器
                    {
                        Readnum = SubStrArry.Length - 1;
                        if (Readnum == 19) Readnum = 20; //for SSD bug can't read 21
                        sendtemstr = "99,26," + SubStrArry[0] + "," + Readnum.ToString("X2");
                        for (int j = 1; j < Readnum; j++)
                        {
                            sendtemstr = sendtemstr + ",00";
                        }
                        packnum = packnum + Readnum;
                        frmHelp.comPort.ReceivedBytesThreshold = 4080;
                        WriteComport(sendtemstr);
                        // Delay(10);
                        readstring = SerialPort_Read(Readnum * 15, out num, out readbuff);
                        if (num > 4) regstring = readstring.Substring(12, (num - 6) * 3 - 1);
                        AddMsgShow(text_scriptRec, ScriptDebugflag, SubStrArry[0] + " " + regstring);

                    }
                }
                //=======兼容chipone 格式===============================================
                else if ((FirstSubstr.Length == 3) && (FirstSubstr.Substring(0, 1) == "R"))
                {
                    if (SubStrArry.Length > 1 && SubStrArry[1].Substring(0, 1) == "#")//++chipone 回读格式
                    {
                        Readnum = Convert.ToByte(SubStrArry[1].Replace("#", ""));
                        if (Readnum == 21) Readnum = 22; //for SSD bug can't read 21
                        temstr = "99,26," + SubStrArry[0].Replace("R", "");
                        temstr += "," + Readnum.ToString("X2");//[1]=register
                        for (int j = 1; j < Readnum; j++)
                        {
                            temstr = temstr + ",00";
                        }
                        frmHelp.comPort.ReceivedBytesThreshold = 4080;
                        Thread.Sleep(5);
                        WriteComport(temstr);
                        readstring = SerialPort_Read(Readnum * 15, out num, out readbuff);
                        if (num > 4) regstring = readstring.Substring(12, (num - 6) * 3 - 1);
                        AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIR " + SubStrArry[0].Replace("R", "") + "=" + regstring);

                    }
                    else//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++chipone write 寄存器格式
                    {
                        temstr = "99 1E " + FirstSubstr.Replace("R", "");//LP_DCS_Long_Write [0],[1]

                        for (int j = 1; j < SubStrArry.Length; j++)
                        {
                            if (SubStrArry[j].Length > 0)
                                temstr = temstr + " " + SubStrArry[j];
                        }
                        WriteComport(temstr);
                        Delay(10);
                        AddMsgShow(text_scriptRec, ScriptDebugflag, subtemstr);
                    }
                }

                //=========Victor 自定义增强解析脚本=================================================
                else
                {
                    switch (FirstSubstr)
                    {
                        case "CLS":// clear Screen
                            {
                                text_scriptRec.Text = "";
                                //text_scriptRec.Text += StrArry[i] + "\r\n"; LCD_cfgInital
                            }
                            break;
                        case "HWRST":// LCM  模组拉RST 动作
                            {
                                frmHelp.LCD_HWRST();
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "HWRST");
                                //text_scriptRec.Text += StrArry[i] + "\r\n"; LCD_cfgInital
                            }
                            break;
                        case "LCM_INITAL":
                            {
                                frmHelp.LCD_cfgInital();
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "LCM_INITAL");
                                //text_scriptRec.Text += StrArry[i] + "\r\n"; LCD_cfgInital
                            }
                            break;
                        case "REGW": //NOvatek 格式
                        case "DSIW":
                            {
                                sendtemstr = "99" + " " + "1C";//LP_DCS_Long_Write [0],[1]
                                                               //subnum = SubStrArry.Length + 1;
                                                               //temstr = temstr + " " + SubStrArry.Length.ToString("X2") ; //no need calc num ,comwrite calc
                                for (int j = 1; j < SubStrArry.Length; j++)
                                {
                                    if (SubStrArry[j].Length > 0)
                                        temstr = temstr + " " + ScriptAsmb(SubStrArry[j]);
                                }
                                sendtemstr = sendtemstr + temstr;
                                WriteComport(sendtemstr);
                                Delay(10);
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIW" + temstr);
                                //text_scriptRec.Text += StrArry[i] + "\r\n";
                            }
                            break;
                        // W6G  格式
                        case "REGS.WRITE(3":
                        case "REGS.WRITE(0":
                            {
                                sendtemstr = "99" + " " + "1C";//LP_DCS_Long_Write [0],[1]
                                                               //subnum = SubStrArry.Length + 1;
                                                               //temstr = temstr + " " + SubStrArry.Length.ToString("X2") ; //no need calc num ,comwrite calc
                                for (int j = 2; j < SubStrArry.Length; j++)
                                {
                                    if (SubStrArry[j].Length > 0)
                                        temstr = temstr + " " + ScriptAsmb(SubStrArry[j].Replace(")", ""));
                                }
                                sendtemstr = sendtemstr + temstr;
                                WriteComport(sendtemstr);
                                Delay(10);
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIW" + temstr);
                                //text_scriptRec.Text += StrArry[i] + "\r\n";
                            }
                            break;
                        case "REGS.READ(0": //W6G 格式    REGS.READ(0, 0x2A, 0x04, @$ReadData) 
                        case "DSIR":
                            {
                                Readnum = Convert.ToByte(SubStrArry[2], 16);
                                if (Readnum == 21) Readnum = 22; //for SSD bug can't read 21
                                sendtemstr = "99,26," + ScriptAsmb(SubStrArry[1]) + "," + ScriptAsmb(SubStrArry[2]);//[1]=register
                                for (int j = 1; j < Readnum; j++)
                                {
                                    sendtemstr = sendtemstr + ",00";
                                }
                                packnum = packnum + Readnum;
                                frmHelp.comPort.ReceivedBytesThreshold = 4080;
                                Delay(5);
                                WriteComport(sendtemstr);
                                readstring = SerialPort_Read(Readnum * 15, out num, out readbuff);
                                if (num > 4) regstring = readstring.Substring(12, (num - 6) * 3 - 1);
                                //readbuff.CopyTo ()
                                // text_scriptRec.Text += "DSIR " + regstring + "\r\n";
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIR " + SubStrArry[1] + "=" + regstring);

                            }
                            break;

                        case "REGR": //DSIC B6 12 23
                            {
                                Readnum = SubStrArry.Length - 2;
                                if (Readnum == 19) Readnum = 20; //for SSD bug can't read 21
                                sendtemstr = "99,26," + SubStrArry[1] + "," + Readnum.ToString("X2");
                                compstring = "";
                                for (int j = 1; j <= Readnum; j++)
                                {
                                    compstring = compstring + " " + SubStrArry[j + 1].ToUpper();
                                    //sendtemstr = sendtemstr + ",00";
                                }
                                packnum = packnum + Readnum;

                                frmHelp.comPort.ReceivedBytesThreshold = 4080;
                                WriteComport(sendtemstr + compstring);
                                // Delay(10);
                                readstring = SerialPort_Read(Readnum * 15, out num, out readbuff);
                                if (num > 4) regstring = readstring.Substring(12, (num - 7) * 3 - 1);
                                compstring = compstring.Replace("0x", "").Replace("0X", "");
                                if (compstring == (" " + regstring))
                                {
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, "REGR " + SubStrArry[1] + " " + regstring + "  //      ==Read OK===");
                                }
                                else
                                {
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, "REGR " + SubStrArry[1] + " " + regstring + "  //      +++Read NG !+++" + "  Correct value：" + SubStrArry[1] + "=" + compstring);
                                }

                                // AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIC " + SubStrArry[1] + " " + regstring);
                            }
                            break;
                        case "DSIC": //DSIC B6 12 23
                            {
                                Readnum = SubStrArry.Length - 2;
                                if (Readnum == 19) Readnum = 20; //for SSD bug can't read 21
                                sendtemstr = "99,26," + SubStrArry[1] + "," + Readnum.ToString("X2");
                                for (int j = 1; j < Readnum; j++)
                                {
                                    sendtemstr = sendtemstr + ",00";
                                }
                                packnum = packnum + Readnum;

                                frmHelp.comPort.ReceivedBytesThreshold = 4080;
                                WriteComport(sendtemstr);
                                // Delay(10);
                                readstring = SerialPort_Read(Readnum * 15, out num, out readbuff);
                                if (num > 4) regstring = readstring.Substring(12, (num - 6) * 3 - 1);
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIC " + SubStrArry[1] + " " + regstring);
                            }
                            break;
                        case "PACKW":
                            {
                                sendtemstr = SubStrArry[1];//LP_DCS_Long_Write [0],[1]
                                for (int j = 2; j < SubStrArry.Length; j++)
                                {
                                    if (SubStrArry[j].Length > 0)
                                        sendtemstr = sendtemstr + " " + SubStrArry[j];
                                }
                                WriteComport(sendtemstr);
                                Delay(10);
                                AddMsgShow(text_scriptRec, ScriptDebugflag, subtemstr);
                                //text_scriptRec.Text += StrArry[i] + "\r\n";
                            }
                            break;
                        case "SCMW":
                            {
                                sendtemstr = "0D 06 06";
                                for (int j = 1; j < SubStrArry.Length; j++)
                                {
                                    if (SubStrArry[j].Length > 0)
                                        temstr = temstr + " " + ScriptAsmb(SubStrArry[j]);
                                }
                                sendtemstr = sendtemstr + temstr;
                                WriteComPortPackage(sendtemstr);
                                Delay(10);
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "SCMW" + temstr);
                                //text_scriptRec.Text += StrArry[i] + "\r\n";
                            }
                            break;
                        case "SOLW":
                            {
                                sendtemstr = "0D 03 03";
                                for (int j = 1; j < SubStrArry.Length; j++)
                                {
                                    if (SubStrArry[j].Length > 0)
                                        temstr = temstr + " " + ScriptAsmb(SubStrArry[j]);
                                }
                                sendtemstr = sendtemstr + temstr;
                                WriteComPortPackage(sendtemstr);
                                Delay(10);
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "SOLW" + temstr);
                                //text_scriptRec.Text += StrArry[i] + "\r\n";
                            }
                            break;
                        case "RGBW":// 切换内置RGB 图片
                            {
                                if (SubStrArry.Length > 3)
                                {
                                    int Tem_R = Convert.ToInt32(ScriptAsmb(SubStrArry[1]));//Convert.ToByte(SubStrArry[1], 16);
                                    int Tem_G = Convert.ToInt32(ScriptAsmb(SubStrArry[2]));
                                    int Tem_B = Convert.ToInt32(ScriptAsmb(SubStrArry[3]));
                                    Pattern_Write(ICGT.ICName, Tem_R, Tem_G, Tem_B, true);
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, "RGBW " + Tem_R.ToString() + " " + Tem_G.ToString() + " " + Tem_B.ToString());
                                }
                                else
                                {
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, "CMD RGBW  error, eg. RGBW,R_value,G_value,B_value");
                                }
                            }
                            break;
                        case "MCOLOR":// 切灰阶，并测试光学数据 COLORM R,G,B,delay
                            {
                                if (SubStrArry.Length > 3)
                                {
                                    int Tem_R = Convert.ToInt32(SubStrArry[1]);//Convert.ToByte(SubStrArry[1], 16);
                                    int Tem_G = Convert.ToInt32(SubStrArry[2]);
                                    int Tem_B = Convert.ToInt32(SubStrArry[3]);
                                    Pattern_Write(ICGT.ICName, Tem_R, Tem_G, Tem_B, false);
                                    if (SubStrArry.Length > 4)
                                    {
                                        Tem_delay = Convert.ToInt32(SubStrArry[4]);
                                        Thread.Sleep(Tem_delay);
                                        CaSDKObj.CASDK_AutoMeasure();
                                        CAS200_AddData(SubStrArry[1] + "," + SubStrArry[2] + "," + SubStrArry[3], CaSDKObj.Lv, CaSDKObj.sx, CaSDKObj.sy, CaSDKObj.T, CaSDKObj.duv, CaSDKObj.X, CaSDKObj.Y, CaSDKObj.Z);

                                    }
                                }
                            }
                            break;
                        case "M410":// 测试光学数据 COLORM R,G,B,delay
                            {
                                CaSDKObj.CASDK_AutoMeasure();
                                CAS200_AddData(subtemstr, CaSDKObj.Lv, CaSDKObj.sx, CaSDKObj.sy, CaSDKObj.T, CaSDKObj.duv, CaSDKObj.X, CaSDKObj.Y, CaSDKObj.Z);
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "Lv=" + CaSDKObj.Lv + ",sx=" + CaSDKObj.sx + ",sy=" + CaSDKObj.sy);
                            }
                            break;
                        case "DELAY":
                            {
                                Readnum = 0;
                                if (SubStrArry.Length > 1)
                                {
                                    temstr = SubStrArry[1];
                                    if (temstr.Length > 2 && (temstr.Substring(temstr.Length - 2, 2) == "ms"))
                                    { Readnum = Convert.ToInt32(temstr.Replace("ms", "")); }
                                    else if (temstr.Length > 1 && (temstr.Substring(temstr.Length - 1, 1) == "s"))
                                    { Readnum = Convert.ToInt32(temstr.Replace("s", "")) * 1000; }
                                    else
                                    { Readnum = Convert.ToInt32(temstr); }

                                    if (Readnum < 100) //小于100 直接系统
                                    { Thread.Sleep(Readnum); }
                                    else
                                    {
                                        temstr = "99 90 00 00";
                                        WriteComport(temstr); //delay 自动将下位机退出读取Lp mode 改为HS
                                        Thread.Sleep(Readnum % 100);
                                        Delayx100ms(Readnum / 100);
                                    }
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, StrArry[i]);
                                }
                            }
                            break;
                        case "ECHO":
                            {
                                markloc = subtemstr.Substring(4, subtemstr.Length - 4).IndexOf("$");  //查找是否含有变量
                                if (markloc >= 0)
                                {
                                    readstring = "";
                                    for (int j = 1; j < SubStrArry.Length; j++)
                                    {
                                        if (SubStrArry[j].Length > 0)
                                            readstring += ScriptAsmb(SubStrArry[j]);
                                    }
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, readstring);
                                }
                                else
                                {
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, subtemstr);
                                }
                            }
                            break;
                        case "LOADBIN":
                            {

                                if (SubStrArry.Length < 6)
                                {
                                    if (MessageBox.Show("LOADBIN should input 5par:1=packtype,2=packsize,3=1st_addr,4=2nd_addr,5=path]" + SubStrArry[1] + "\r\n continue run?", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                                    { goto Endfunction; }
                                }
                                else
                                {
                                    if (!File.Exists(SubStrArry[5]))
                                    {
                                        if (MessageBox.Show("[Not Found File:]" + SubStrArry[5] + "\r\n continue run?", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                                        { goto Endfunction; }
                                    }
                                    // int result = SendDemura_fromfile(SubStrArry[1]);
                                    temstr = "99 90 00 00"; //切回高速
                                    WriteComport(temstr);
                                    int result = GenDemura_fromfile(SubStrArry[1], SubStrArry[2], SubStrArry[3], SubStrArry[4], SubStrArry[5]);
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, subtemstr);
                                    if ((result == 0) && (MessageBox.Show("[Load Bin to DDIC fail]" + "\r\n continue run?", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No))
                                    { goto Endfunction; }
                                }
                            }
                            break;

                        case "LOADBINASPIC":
                        case "LOADPIC":
                            {
                                string tempptah = SubStrArry[1];
                                //路径部分添加 变量支持
                                markloc = subtemstr.Substring(4, subtemstr.Length - 4).IndexOf("$");  //查找是否含有变量
                                if (markloc >= 0)
                                {
                                    readstring = "";
                                    for (int j = 1; j < SubStrArry.Length; j++)
                                    {
                                        if (SubStrArry[j].Length > 0)
                                            readstring += ScriptAsmb(SubStrArry[j]);
                                    }
                                    tempptah = readstring;
                                }
                                else
                                {
                                    tempptah = SubStrArry[1];
                                }                                    //路径部分添加 变量支持end
                                if (!File.Exists(tempptah))
                                {
                                    if (MessageBox.Show("[Not Found File:]" + tempptah + "\r\n continue run?", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                                    { goto Endfunction; }

                                }
                                else
                                {
                                    temstr = "99 90 00 00"; //切回高速
                                    WriteComport(temstr);
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, "LOADPIC " + tempptah);
                                    int result = 0;
                                    if (FirstSubstr == "LOADBINASPIC")
                                    {
                                        result = LoadBinAsPic(tempptah);
                                    }
                                    else
                                    {
                                        result = LoadPic(tempptah);
                                    }
                                    if ((result == 0) && (MessageBox.Show("[Load Pic]" + "\r\n continue run?", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No))
                                    { goto Endfunction; }
                                }
                            }
                            break;

                        case "LOADMRC":
                            {
                                string tempptah = SubStrArry[1];
                                //路径部分添加 变量支持
                                markloc = subtemstr.Substring(4, subtemstr.Length - 4).IndexOf("$");  //查找是否含有变量
                                if (markloc >= 0)
                                {
                                    readstring = "";
                                    for (int j = 1; j < SubStrArry.Length; j++)
                                    {
                                        if (SubStrArry[j].Length > 0)
                                            readstring += ScriptAsmb(SubStrArry[j]);
                                    }
                                    tempptah = readstring;
                                }
                                else
                                {
                                    tempptah = SubStrArry[1];
                                }
                                //路径部分添加 变量支持end
                                if (!File.Exists(tempptah))
                                {
                                    if (MessageBox.Show("[Not Found File:]" + tempptah + "\r\n continue run?", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                                    { goto Endfunction; }

                                }
                                else
                                {
                                    AddMsgShow(text_scriptRec, ScriptDebugflag, "LOADMCR " + tempptah);
                                    Write6AComport_Script(loadScriptFromfile(tempptah), HF_GenW_port);
                                    //int result = LoadPic(tempptah);
                                    //if ((result == 0) && (MessageBox.Show("[Load Pic]" + "\r\n continue run?", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No))
                                    //{ goto Endfunction; }
                                }
                            }
                            break;
                        case "LOOP":
                            {
                                loopnum[0] += 1;
                                loopnum[loopnum[0]] = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16);
                                looploc[loopnum[0]] = i;//记录当前行
                            }
                            break;
                        case "LOOPEND":
                            {
                                //loopnum[0] += 1;
                                loopnum[loopnum[0]] -= 1;
                                if (loopnum[loopnum[0]] > 0)
                                { i = looploc[loopnum[0]]; }//返回loop code line    
                                else
                                { loopnum[0] -= 1; }
                            }
                            break;
                        case "ONLYW"://定义只写寄存器比如nova 家的F0，6F,2F,发方便在2K 格式代码自动判断支持
                            {
                                if (SubStrArry.Length > 1)
                                    ONLYW_RegString = subtemstr.ToUpper();
                                else  //关闭自动回读功能
                                {
                                    ONLYW_RegString = "";
                                    Writemode = 0;
                                }
                            }
                            break;

                        case "PUSH"://字符串buff 
                            {
                                if (SubStrArry[1].Substring(0, 5) == "$BUFF")
                                {
                                    num = Convert.ToInt32(SubStrArry[1].Substring(5, SubStrArry[1].Length - 5));
                                    mathvalue = 2;
                                    if (SubStrArry[2] == "=") //赋值，则把之前清空
                                    {
                                        Msgbuff[num] = "";
                                        mathvalue = 3;
                                    }
                                    else if (SubStrArry[2] == "+") //追加，则保留之前数据
                                    {
                                        mathvalue = 3;
                                    }
                                    for (int j = mathvalue; j < SubStrArry.Length; j++)
                                    {
                                        if (SubStrArry[j].Length > 0)
                                            Msgbuff[num] += " " + ScriptAsmb(SubStrArry[j]);
                                    }
                                }
                            }
                            break;
                        case "MATH": //数学运算      eg:Math $HEX2 = $HEX3
                            {
                                int datatype = 10;
                                num = Convert.ToInt32(SubStrArry[1].Substring(5, SubStrArry[1].Length - 5));
                                mathvalue = 0;
                                if (SubStrArry[1].Substring(0, 5).ToUpper() == "$NHEX")
                                { datatype = 16; }
                                if (SubStrArry[1].Substring(0, 5).ToUpper() == "$NDEC")
                                { datatype = 10; }
                                switch (SubStrArry[2].ToUpper())
                                {
                                    case "=": //赋值
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case "+": //加法
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) + Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case "-"://减法
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) - Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case "*"://乘法
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) * Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case "/"://除法
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) / Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case "&"://位与
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) & Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case "|"://或运算
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) | Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case "%"://取余
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) % Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case ">>"://右移位
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) >> Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                    case "<<"://左移位
                                        mathvalue = Convert.ToInt32(ScriptAsmb(SubStrArry[1]), 16) << Convert.ToInt32(ScriptAsmb(SubStrArry[3]), 16);
                                        break;
                                }
                                if (SubStrArry[1].Substring(0, 5).ToUpper() == "$NHEX")
                                { Nhex[num] = mathvalue; }
                                if (SubStrArry[1].Substring(0, 5).ToUpper() == "$NDEC")
                                { Ndec[num] = mathvalue; }
                            }
                            break;
                        case "MSG":
                            {
                                if (MessageBox.Show(subtemstr + "\r\n continue run?", "Confirm Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                                { goto Endfunction; }
                            }
                            break;
                        case "SOUND":
                            {
                                if (SubStrArry.Length > 1)
                                {
                                    if (SubStrArry[1] == "0") System.Media.SystemSounds.Beep.Play();
                                    if (SubStrArry[1] == "1") System.Media.SystemSounds.Hand.Play();
                                    if (SubStrArry[1] == "2") System.Media.SystemSounds.Question.Play();
                                }
                                else
                                {
                                    System.Media.SystemSounds.Beep.Play();
                                }
                            }
                            break;
                        case "HELP":
                            {
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "CMD list:");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "HWRST..........................Driver IC 做硬件复位动作");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "LCM_INITAL.....................OLED模组下发初始化");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "XX,XX,XX,......................2K 格式写寄存器(eg.F0,55,aa,52,08,02)");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIW Reg Par1 PAr2.............写寄存器eg:DSIW 9f,03");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "DSIR Reg Num...................读寄存器eg:DSIR B1,04 回读b1 寄存器4个参数");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "PACKW xx xx....................串口发送pack eg:5D 01 xx(no include packnum)");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "LOADBIN Path...................Load demura bin to DDIC RAM ");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "LOADPIC Path...................DownLoad PicPath 图片并显示");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "LOADMCR Path...................加载脚本文件，并解释执行");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "RGBW R,G,B,[delay].............显示RGB 纯色画面并调用CA410 测试光学数据;eg: MCOLOR 255,127,255");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "MCOLOR R,G,B,[delay]...........显示RGB 纯色画面并调用CA410 测试光学数据;eg: MCOLOR 255,127,255");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "M410  .........................调用CA410 测试光学数据");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "DELAY xxx......................延时命令xxx为10进制 默认ms也可 DELAY 10s");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "MSG information................弹出消息框，提示information,Yes 继续运行，No =直接结束");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "CLS............................清除Script MSG 显示区内容");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "ECHO information...............Script MSG 显示information（不弹窗）");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "PUSH BUFF1.....................将字符串内容压缩至buff 数组内");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "ONLYW REG1,REG2................自动回读本行代码之后的所有寄存器，除了REG1，REG2.. 为写，REG用于切page");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "REGW Reg Par1 PAr2.............NOVATEK写寄存器eg:REGW 9f,03");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "REGS.WRITE(0,0x39,0xEC,0x00)...W6/W6G写寄存器eg:REGS.WRITE(0,0x39,0xEC,0x00)");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "Rxx xx.........................CHIPONE写寄存器eg:R9f,03");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "Rxx #xx........................CHIPONE读寄存器eg:R9f,#12");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "变量及数学运算:");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "MATH $HEX2 = $HEX3.............数学运算命令，=可替换为+,-,*,/,&,|,%,>>,<<");
                                AddMsgShow(text_scriptRec, ScriptDebugflag, "$HEX2..........................16进制的数学变量符号");
                            }
                            break;
                        default:
                            break;
                    }
                }

            }
            //temstr = "6A 20 " + packnum.ToString("X2");

            temstr = "99 90 00 00";

            WriteComport(temstr);
            code_out.Insert(0, temstr);
            code_out.Append("\r\n");

        Endfunction:
            return code_out.ToString();
            // return temstr;
        }

        private string ScriptAsmb(string inputcell)//srcipt 变量管理器以$ 开头标志
        {
            string return_str = "Null"; //变量名统一长度统一为4，,后面跟数字，如$READ1,$READ2,$BUFF1,$BUFF2
            if ((inputcell.Length > 4) && (inputcell.Substring(0, 1) == "$"))
            {
                string cellhead = inputcell.Substring(0, 5).ToUpper();
                int cellindex = Convert.ToInt32(inputcell.Substring(5, inputcell.Length - 5));
                switch (cellhead)
                {
                    case "$READ":
                        return_str = readbuff[cellindex + 3].ToString("X2");
                        break;
                    case "$NHEX":
                        return_str = Nhex[cellindex].ToString("X2");
                        break;
                    case "$NDEC":
                        return_str = Ndec[cellindex].ToString();
                        break;
                    case "$BUFF":
                        return_str = Msgbuff[cellindex];
                        break;
                }

            }
            else// 不是变量是data / 分为整形 #1000
            {
                if (inputcell == "#ENTER")//回车
                {
                    return_str = "\r\n";
                }
                else if (inputcell == "#SPEC")//空格
                {
                    return_str = " ";
                }
                else if ((inputcell.Length > 1) && (inputcell.Substring(0, 1) == "#"))//# 开头10进制
                {
                    return_str = Convert.ToInt32(inputcell.Substring(1, inputcell.Length - 1)).ToString("X2");
                }
                else if ((inputcell.Length > 2) && ((inputcell.Substring(0, 2) == "0X") || (inputcell.Substring(0, 2) == "0x")))//0X 16 进制
                {
                    return_str = Convert.ToInt32(inputcell.Substring(2, inputcell.Length - 2), 16).ToString("X2");
                }
                else return_str = inputcell;
            }
            return return_str;

        }
        #endregion


        #region//切图单元 // pattern

        private void Pattern_Write(string Bist_ICname, int R_value, int G_value, int B_value, bool Flaginital)//重构兼容IC bist 切图
        {
            string cmdcode = "";
            switch (Bist_ICname)
            // "99" + " " + "1E";
            {
                case "ICNA3511":         //3511 支持bist,切RGB 配比画面DSIW,9F,01;DSIW,C6,03;
                    {
                        if (Flaginital)
                        {
                            WriteComport("99,1E,9F,01"); //3511 下9f,01
                            WriteComport("99,1E,C6,03"); //3511 下C6,03
                        }
                        cmdcode = "99" + "," + "1E" + " " + "C7 " + R_value.ToString("X2") + "," + G_value.ToString("X2") + "," + B_value.ToString("X2");
                        WriteComport(cmdcode);
                    }
                    break; //BL
                default:
                    {
                        Send_buf = new byte[25];
                        Setting.TempRecord.cmdLen = 25;
                        Send_buf[0] = 0x0A; //LCD配置标志
                        Send_buf[2] = 0x15; //数据长度
                        Send_buf[1] = 0x07;
                        Send_buf[3] = (byte)R_value;
                        Send_buf[4] = (byte)G_value;
                        Send_buf[5] = (byte)B_value;
                        CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
                        try
                        {
                            frmHelp.comPort.Write(Send_buf, 0, 25);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                        }
                    }
                    // Pattern_Write( R_value,  G_value,  B_value);
                    break; //BL
            }

        }

        private void Pattern_Write(int R_value, int G_value, int B_value)//重构for int gray >8 bit
        {
            //numPattern_R.Value = R_value;
            //numPatternG.Value = G_value;
            //numPatternB.Value = B_value;
            Send_buf = new byte[25];
            Setting.TempRecord.cmdLen = 25;
            Send_buf[0] = 0x0A; //LCD配置标志
            Send_buf[2] = 0x15; //数据长度
            Send_buf[1] = 0x07;
            Send_buf[3] = (byte)R_value;
            Send_buf[4] = (byte)G_value;
            Send_buf[5] = (byte)B_value;

            CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);

            frmHelp.comPort.Write(Send_buf, 0, 25);

            /*
             // 子函数不进行错误处理，放在调用函数
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 25);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            */
        } //重构for int gray >8 bit end

        private void Pattern_Write(int R_value, int G_value, int B_value, string subpicpath)//重构for 图片调gamma,测试gamma
        {

            string picname = "";
            if (subpicpath != "")
            {
                picname = subpicpath + R_value.ToString("X2") + G_value.ToString("X2") + B_value.ToString("X2") + ".bmp";
                //picname = subpicpath + "\\" + R_value.ToString("X2") + G_value.ToString("X2") + B_value.ToString("X2") + ".bmp";

                if (File.Exists(picname)) LoadPic(picname);
                else Err_report += "not found pic path: picname";
            }
            else
            {
                Pattern_Write(R_value, G_value, B_value);
            }


            //  Picpath
        } //重构for int gray >8 bit end

        /*
         
             private void Pattern_Write(byte R_value, byte G_value, byte B_value)
        {
            numPattern_R.Value = R_value;
            numPattern_G.Value = G_value;
            numPattern_B.Value = B_value;
            OLED_Show_Click(btnPatternW, null);
        }
        */
        private void radioButton_PatternGray_Click(object sender, EventArgs e)
        {
            RadioButton temRb = (RadioButton)sender;
            if (temRb.Name == "radioButton_Mix")
            {
                numPattern_W.Visible = false;
                numPattern_W.Tag = 7;
            }
            else
            {
                numPattern_W.Visible = true;
            }

            PureColor_Show();
        }

        private void radioButton_PatternColor_Click(object sender, EventArgs e)
        {
            RadioButton temRb = (RadioButton)sender;
            if (temRb.Name == "radioButton_Mix")
            {
                numPattern_W.Visible = false;
                numPattern_W.Tag = 7;
            }
            else
            {
                numPattern_W.Visible = true;
            }

            PureColor_Show();
        }

        private void Gray_fastChange(object sender, EventArgs e)
        {
            RadioButton temRb = (RadioButton)sender;
            int temgray = Convert.ToInt32(temRb.Text);
            numPattern_W.Value = numPattern_R.Value = numPattern_G.Value = numPattern_B.Value = temgray;
            PureColor_Show();
        }

        private void OLED_Show_Click(object sender, EventArgs e)
        {
            PureColor_Show();
        }

        private void PureColor_Show()
        {
            if (radioButton_W.Checked == true)
            {
                numPattern_R.Value = numPattern_W.Value; numPattern_G.Value = numPattern_W.Value; numPattern_B.Value = numPattern_W.Value;
            }
            if (radioButton_R.Checked == true)
            {
                numPattern_R.Value = numPattern_W.Value; numPattern_G.Value = 0; numPattern_B.Value = 0;
            }
            if (radioButton_G.Checked == true)
            {
                numPattern_R.Value = 0; numPattern_G.Value = numPattern_W.Value; numPattern_B.Value = 0;
            }
            if (radioButton_B.Checked == true)
            {
                numPattern_R.Value = 0; numPattern_G.Value = 0; numPattern_B.Value = numPattern_W.Value;
            }
            int Tem_R = (Int32)numPattern_R.Value;
            int Tem_G = (Int32)numPattern_G.Value;
            int Tem_B = (Int32)numPattern_B.Value;
            string ICname = "BISTOFF";
            if (checkBox_Pattern_Bist.Checked == true) ICname = ICGT.ICName;
            if (!frmHelp.comPort.IsOpen)
            {
                try
                {
                    frmHelp.comPort.PortName = Detection.GetComNum();
                    frmHelp.comPort.BaudRate = Setting.ComSet.comBaudRate;
                    frmHelp.openSerialPort(true);
                    Pattern_Write(ICname, Tem_R, Tem_G, Tem_B, true);
                }
                catch
                {
                    MessageBox.Show("没有搜索到串口！", "错误提示");
                }
            }
            else
            {
                Pattern_Write(ICname, Tem_R, Tem_G, Tem_B, true);
            }

        }

        //浏览图片
        string defaultfilePath = "";
        string path = "";
        private void btnBrowsePic_Click(object sender, EventArgs e)    //载入画面按键  选择文件夹
        {
            string Userpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG";
            string defualtinfPath = Userpath + "\\Lastlog.inf";
            bool result;
            string tempath = ReadIni("Lastlog", "2KPicPath", defualtinfPath);
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择
            if ((tempath != "") && Directory.Exists(tempath))
            {
                fldb.SelectedPath = tempath;
                fldb.ShowNewFolderButton = false;
                DialogResult res = fldb.ShowDialog();

                path = fldb.SelectedPath;
                DirectoryInfo di = new DirectoryInfo(path);
                this.listBox3_BMPFile.Items.Clear();
                this.CreateListItem(di);//递归加载文件夹里的所有图片
                textBox2.Text = path;
                checkBox_Pattern_Pic_Click(sender, e);
                result = WritePrivateProfileString("Lastlog", "2KPicPath", path, defualtinfPath);
            }
            else
            {
                fldb.ShowNewFolderButton = false;
                DialogResult res = fldb.ShowDialog();
                if (res != System.Windows.Forms.DialogResult.OK)
                {
                    MessageBox.Show("没选择任何文件夹.");
                    return;
                }
                defaultfilePath = fldb.SelectedPath;//记录选中的目录
                path = fldb.SelectedPath;
                if (!Directory.Exists(path))
                {
                    MessageBox.Show("文件夹不存在.");
                    return;
                }
                DirectoryInfo di = new DirectoryInfo(path);
                this.listBox3_BMPFile.Items.Clear();
                this.CreateListItem(di);//递归加载文件夹里的所有图片
                textBox2.Text = path;
                result = WritePrivateProfileString("Lastlog", "2KPicPath", path, defualtinfPath);
            }
        }
        /// <summary>
        /// 递归文件夹，把文件夹里所有后缀类似图片的文件，加入listbox
        /// </summary>
        /// <param name="di"></param>
        private void CreateListItem(DirectoryInfo di)
        {
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem(childDi);
            }
            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    this.listBox3_BMPFile.Items.Add(new MyImage(fi.FullName));
                }
            }
        }


        private void lstImage_Click(object sender, EventArgs e)
        {
            if (listBox3_BMPFile.SelectedItem == null)
            {
                return;
            }
            MyImage selectedImg = (MyImage)listBox3_BMPFile.SelectedItem;
            //Image img = new Bitmap(selectedImg.Path);
            //pictureBox1.Image = img;
            FileStream fileStream = new FileStream(selectedImg.Path, FileMode.Open, FileAccess.Read);
            pictureBox1.Image = Image.FromStream(fileStream);
            fileStream.Dispose(); //释放资源
            fileStream.Close();
        }     //单击击 预览 BMP图片



        private void btnPrevPic_Click(object sender, EventArgs e)       //双击 载入 BMP图片
        {
            Int32 HACT_True = 0;
            Int32 HACT_Skip = 0;
            Int32 VACT_True = 0;
            Int32 m_txlen = 0;
            Int32 j = 0;
            FileStream aFile;

            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;

            //string FileName = textBox2.Text + '\\' + listBox3_BMPFile.SelectedItem.ToString();
            MyImage FileName = (MyImage)listBox3_BMPFile.SelectedItem;
            aFile = new FileStream(FileName.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            ByteReaded = aFile.Read(TemFileContent, 0, 54);

            HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
            VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);


            {
                if ((frmHelp.Dis_mode.SelectedIndex == 1)) //video
                {
                    HACT_Skip = HACT_True % 10 > 0 ? (HACT_True + 10 - HACT_True % 10) : HACT_True;
                }
                else
                {
                    HACT_Skip = HACT_True;
                }
                try
                { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                    TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                    frmHelp.comPort.Write(TemFileContent, 0, 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
                //-----------------------------------
                try
                {
                    //HACT_True = Sig_mode.SelectedIndex > 2 ? Convert.ToInt32(2 * ((TemFileContent[19]<<8)+ TemFileContent[18])) : Convert.ToInt32((TemFileContent[19] << 8) + TemFileContent[18]);
                    j = 1;
                    while (j <= VACT_True)
                    {
                        if (HACT_True % 4 != 0)
                            aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
                        else
                            aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);

                        ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                        try
                        {
                            frmHelp.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                            break;
                        }
                        m_txlen += ByteReaded;
                        progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                        label17.Text = progressBar1.Value.ToString() + "%";
                        Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                        j++;

                    }
                    TemFileContent[0] = 0x5A;
                    try
                    {
                        frmHelp.comPort.Write(TemFileContent, 0, 1);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        return;
                    }
                    aFile.Dispose();
                    aFile.Close();
                }
                catch
                {
                    label17.Text += "啥图片都没显示";
                    // textBox1.Select(textBox1.Text.Length, 0);
                    // textBox1.ScrollToCaret();
                }
            }
        }
        private int LoadBinAsPic(string picpath)       //双击 载入 BMP图片
        {
            Int32 HACT_True = 0;
            Int32 HACT_Skip = 0;
            Int32 VACT_True = 0;
            Int32 m_txlen = 0;
            Int32 j = 0;
            // FileStream aFile;

            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;

            string FileName = picpath;
            FileStream aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            ByteReaded = aFile.Read(TemFileContent, 0, 54);
            HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
            VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);
            {
                if ((frmHelp.Dis_mode.SelectedIndex == 1)) //video
                {
                    HACT_Skip = HACT_True % 10 > 0 ? (HACT_True + 10 - HACT_True % 10) : HACT_True;
                }
                else
                {
                    HACT_Skip = HACT_True;
                }
                try
                { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                    TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                    frmHelp.comPort.Write(TemFileContent, 0, 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return 0;
                }
                //-----------------------------------
                try
                {
                    //HACT_True = Sig_mode.SelectedIndex > 2 ? Convert.ToInt32(2 * ((TemFileContent[19]<<8)+ TemFileContent[18])) : Convert.ToInt32((TemFileContent[19] << 8) + TemFileContent[18]);
                    j = 1;
                    while (j <= VACT_True)
                    {


                        if (HACT_True % 4 != 0)
                            aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
                        else
                            aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);

                        ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                        try
                        {
                            frmHelp.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                            return 0;
                            //break;
                        }
                        m_txlen += ByteReaded;
                        progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                        label17.Text = progressBar1.Value.ToString() + "%";
                        Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                        j++;

                    }

                    TemFileContent[0] = 0x5A;
                    try
                    {
                        frmHelp.comPort.Write(TemFileContent, 0, 1);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        return 0;
                    }
                    aFile.Dispose();//释放资源
                    aFile.Close();
                }
                catch
                {
                    label17.Text += "啥图片都没显示";
                    // textBox1.Select(textBox1.Text.Length, 0);
                    // textBox1.ScrollToCaret();
                    return 0;
                }
                return 1;
            }

        }
        private int LoadPic(string picpath)       //双击 载入 BMP图片
        {
            Int32 HACT_True = 0;
            Int32 HACT_Skip = 0;
            Int32 VACT_True = 0;
            Int32 m_txlen = 0;
            Int32 j = 0;
            // FileStream aFile;

            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;

            string FileName = picpath;
            FileStream aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            ByteReaded = aFile.Read(TemFileContent, 0, 54);
            HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
            VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);
            {
                if ((frmHelp.Dis_mode.SelectedIndex == 1)) //video
                {
                    HACT_Skip = HACT_True % 10 > 0 ? (HACT_True + 10 - HACT_True % 10) : HACT_True;
                }
                else
                {
                    HACT_Skip = HACT_True;
                }
                try
                { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                    TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                    frmHelp.comPort.Write(TemFileContent, 0, 5);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return 0;
                }
                //-----------------------------------
                try
                {
                    //HACT_True = Sig_mode.SelectedIndex > 2 ? Convert.ToInt32(2 * ((TemFileContent[19]<<8)+ TemFileContent[18])) : Convert.ToInt32((TemFileContent[19] << 8) + TemFileContent[18]);
                    j = 1;
                    while (j <= VACT_True)
                    {


                        if (HACT_True % 4 != 0)
                            aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
                        else
                            aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);

                        ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                        try
                        {
                            frmHelp.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                            return 0;
                            //break;
                        }
                        m_txlen += ByteReaded;
                        progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                        label17.Text = progressBar1.Value.ToString() + "%";
                        Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                        j++;

                    }

                    TemFileContent[0] = 0x5A;
                    try
                    {
                        frmHelp.comPort.Write(TemFileContent, 0, 1);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        return 0;
                    }
                    aFile.Dispose();//释放资源
                    aFile.Close();
                }
                catch
                {
                    label17.Text += "啥图片都没显示";
                    // textBox1.Select(textBox1.Text.Length, 0);
                    // textBox1.ScrollToCaret();
                    return 0;
                }
                return 1;
            }

        }

        public class MyImage
        {
            public MyImage(string p)
            {
                this.Path = p;
            }
            public string Path { get; set; }
            public override string ToString()
            {
                if (Path == null)
                {
                    return null;
                }
                return System.IO.Path.GetFileName(this.Path);
            }
        }

        #endregion 

        #region //自动测试gamma CA310 410 part
        //= new Timer;

        double Grmaxlum, Grminlum, nowlum;
        double GammaRat = 2.2;
        double[] GC_Lv = new double[1026];//GammaCurve
        int[] GC_gray = new int[1026];//GammaCurve
        double[,] Target_XYZ; //X,Y,Z 目标值0=X,1=Y,2=Z,3=X+Y+Z,4=up_Y,5=low_Y;
        NodeTargetType[] Nodetarget;
        double[,] Target_Limit; //记录nit,rate,lv_limit,x_limit,y_limit

        int[] GrayTune_loopnum = new int[256];//记录每个灰阶允许最大调试次数
        //double[] Target_Y ;
        //double[] Target_Z ;
        int step = 15;


        int measure_Num, SelId;
        private void Inital_Paint(int mapW, int mapH)
        {
            int xoff = 40;
            int yoff = 30;
            double xscaler = mapW - 2 * xoff;
            double yscaler = mapH - 2 * yoff;
            bMap = new Bitmap(mapW, mapH);
            Graphics gph = Graphics.FromImage(bMap);
            Pen xupen = new Pen(Color.Black, 1);
            Font myfont = new Font("宋体", 10);
            gph.Clear(AGengamma.DefaultBackColor);
            PointF cPt = new PointF(xoff, mapH - yoff);
            //X 轴
            gph.DrawLine(Pens.Black, cPt.X, cPt.Y, mapW - xoff, cPt.Y);
            gph.DrawLine(Pens.Black, cPt.X, yoff, mapW - xoff, yoff);
            double xloc = 0;
            xupen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
            xupen.DashPattern = new float[] { 3, 3 };
            for (int i = 0; i < 17; i++)
            {
                xloc = xoff + xscaler / 16 * i;
                gph.DrawLine(xupen, (int)xloc, yoff, (int)xloc, mapH - yoff + 8);
                gph.DrawString((i * 16).ToString(), myfont, Brushes.Black, new PointF((int)xloc - 10, mapH - yoff + 8));
            }
            //Y 轴
            gph.DrawLine(Pens.Black, cPt.X, cPt.Y, cPt.X, yoff);
            gph.DrawLine(Pens.Black, mapW - xoff, cPt.Y, mapW - xoff, yoff);
            for (int i = 0; i < 11; i++)
            {
                xloc = yoff + yscaler / 10 * i;
                gph.DrawLine(xupen, xoff - 5, (int)xloc, mapW - xoff + 10, (int)xloc);
                gph.DrawString((1 - 0.1 * i).ToString(), myfont, Brushes.Black, new PointF(xoff - 38, (int)xloc - 8));
                gph.DrawString((GammaRat + 0.5 - i * 0.1).ToString(), myfont, Brushes.Chocolate, new PointF(mapW - xoff + 10, (int)xloc - 8));
            }


            Pen Uppen = new Pen(Color.Blue, 1);
            Pen Downpen = new Pen(Color.Red, 1);
            Pen Targepen = new Pen(Color.Green, 1);
            double x1, y1, x2, y2;
            xupen.DashPattern = new float[] { 50, 5 };


            gph.DrawLine(Uppen, 170, 15, 220, 15);
            gph.DrawString("Gamma " + (GammaRat - 0.2).ToString(), myfont, Brushes.Blue, new PointF(70, 10));
            gph.DrawLine(Targepen, 370, 15, 420, 15);
            gph.DrawString("Gamma " + (GammaRat).ToString(), myfont, Brushes.Green, new PointF(270, 10));
            gph.DrawLine(Downpen, 570, 15, 620, 15);
            gph.DrawString("Gamma " + (GammaRat + 0.2).ToString(), myfont, Brushes.Red, new PointF(470, 10));
            xupen.DashPattern = new float[] { 5, 5 };
            for (int i = 1; i < xscaler; i++)
            {
                x1 = i - 1; x2 = i;
                y1 = mapH - yoff - Math.Pow((x1 / xscaler), GammaRat - 0.2) * yscaler;
                y2 = mapH - yoff - Math.Pow((x2 / xscaler), GammaRat - 0.2) * yscaler;
                gph.DrawLine(Uppen, (int)(xoff + x1), (int)y1, (int)(xoff + x2), (int)y2);

                y1 = mapH - yoff - Math.Pow((x1 / xscaler), GammaRat) * yscaler;
                y2 = mapH - yoff - Math.Pow((x2 / xscaler), GammaRat) * yscaler;
                gph.DrawLine(Targepen, (int)(xoff + x1), (int)y1, (int)(xoff + x2), (int)y2);

                y1 = mapH - yoff - Math.Pow((x1 / xscaler), GammaRat + 0.2) * yscaler;
                y2 = mapH - yoff - Math.Pow((x2 / xscaler), GammaRat + 0.2) * yscaler;
                gph.DrawLine(Downpen, (int)(xoff + x1), (int)y1, (int)(xoff + x2), (int)y2);
                i = i + 3;
            }


            pictureBox2.Image = bMap;
        }

        private void Update_Paint()
        {

            double x1, y1, x2, y2;
            Bitmap newbMap = bMap;
            int mapW = bMap.Width;
            int mapH = bMap.Height;
            int xoff = 40;
            int yoff = 30;
            double xscaler = mapW - 2 * xoff;
            double yscaler = mapH - 2 * yoff;
            double temx, temy;
            Graphics gph = Graphics.FromImage(newbMap);

            Pen Uppen = new Pen(Color.Black, 1);
            if ((GC_gray[0] > 0) && (GC_Lv[1] != null))
            {
                temx = GC_gray[1];
                temy = GC_Lv[1];
                x1 = xoff + temx / 255 * xscaler;
                y1 = mapH - yoff - temy * yscaler;
                for (int i = 1; i <= GC_gray[0]; i++)
                {
                    temx = GC_gray[i];
                    temy = GC_Lv[i];
                    x2 = xoff + temx / 255 * xscaler;
                    y2 = mapH - yoff - temy * yscaler;
                    gph.DrawLine(Uppen, (int)(x1), (int)y1, (int)(x2), (int)y2);
                    x1 = xoff + temx / 255 * xscaler;
                    y1 = mapH - yoff - temy * yscaler;
                }
            }

            pictureBox2.Image = newbMap;
        }
        private void btn_CASDK_unlink_Click(object sender, EventArgs e)
        {
            try
            {
                if ((CA_Sel.SelectedIndex == 0) | (CA_Sel.SelectedIndex == 1))
                {
                    frmHelp.CaSDKObj.Disconnect();
                }
                else if (CA_Sel.SelectedIndex == 2)
                {
                    frmHelp.CMadj.CMA01_Disconnect();
                }
                btnCal_manual.Enabled = true;
            }
            catch (Exception EX)
            {
                btnCal_manual.Enabled = true;
                MessageBox.Show("CA310/410 Connect Fail!!" + EX.Message);
            }
        }
        private void CaSDK_Measure_Speed_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (CaSDK_Measure_Speed.SelectedIndex == 0) frmHelp.CaSDKObj.ca310speed = 3; //AUTO
            else if (CaSDK_Measure_Speed.SelectedIndex == 1) frmHelp.CaSDKObj.ca310speed = 1; //FAST
            else if (CaSDK_Measure_Speed.SelectedIndex == 2) frmHelp.CaSDKObj.ca310speed = 0; //SLOW
            else if (CaSDK_Measure_Speed.SelectedIndex == 3) frmHelp.CaSDKObj.ca310speed = 2; //LTD_AUTO
        }

        private void btnCal_manual_Click(object sender, EventArgs e)
        {
            btnCal_manual.Enabled = false;
            try
            {
                if (CA_Sel.SelectedIndex == 0)
                {
                    Pattern_Write(0, 0, 0);
                    Pattern_Write(ICGT.ICName, 0, 0, 0, true);
                    frmHelp.CaSDKObj.CA310_Connect();
                    frmHelp.CaSDKObj.CA310_Initial(byte.Parse(CA310_Channel.Text));

                    //CaSDKObj.CA310_Connect();
                    //CaSDKObj.CA310_Initial(byte.Parse(CA310_Channel.Text));
                    btnCal_manual.Enabled = true;
                }
                else if (CA_Sel.SelectedIndex == 1)
                {
                    //Pattern_Write(ICGT.ICName, 0, 0, 0, true);
                    //  Pattern_Write( 0, 0, 0); // CA410 no need change gray0 pattern
                    frmHelp.CaSDKObj.AutoConnect();
                    frmHelp.CaSDKObj.SingleCalibration(0, byte.Parse(CA310_Channel.Text), double.Parse(CA410_Measure_Freq.Text));
                    btnCal_manual.Enabled = true;
                }
                else if (CA_Sel.SelectedIndex == 2)//JC_EYE2_402
                {
                    byte CASDK_MODE = 0;
                    //if (cbo_CASDK_MODE2.SelectedIndex == 0) //Lvxy
                    //{
                    CASDK_MODE = 0;
                    //}
                    //else if (cbo_CASDK_MODE2.SelectedIndex == 1) //JETIA(flicker)
                    //{
                    //    CASDK_MODE = 8;
                    //}
                    //frmHelp.OLED_Show_Click(btnblack, null);
                    frmHelp.Eye402Obj.EYE2_402_AutoConnect();
                    frmHelp.Eye402Obj.EYE2_402_SingleCalibration(CASDK_MODE, byte.Parse(CA310_Channel.Text), double.Parse(CA410_Measure_Freq.Text));
                }
                else if (CA_Sel.SelectedIndex == 3)
                {
                    int temp = 0;
                    temp = frmHelp.CMadj.CMA01_AutoConnect();
                    if (temp == 1)
                    {
                        text_RecMsg.Text += "CMA10连接成功！！！\r\n";
                        btnCal_manual.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("连接失败", "错误");
                    }
                }
                //group_CA.Enabled = true;
            }
            catch (Exception EX)
            {
                btnCal_manual.Enabled = true;
                MessageBox.Show("CA310/410 Connect Fail!!" + EX.Message);
            }
        }

        private void btn_CASDK_Measure_Click(object sender, EventArgs e)
        {
            if (Lockedflag == true) return;
            Lockedflag = true;
            CaSDKObj.CASDK_AutoMeasure();
            //text_Measure_result.Text = CaSDKObj.Lv.ToString()+ ","+ CaSDKObj.sx.ToString() + "," +CaSDKObj.sy.ToString();
            text_Measure_result.Text = String.Format("{0:N3}", CaSDKObj.Lv) + "," + String.Format("{0:N3}", CaSDKObj.sx) + "," + String.Format("{0:N3}", CaSDKObj.sy) + "," + String.Format("{0:N3}", CaSDKObj.X) + "," + String.Format("{0:N3}", CaSDKObj.Z) + ",";
            toolStripStatusLabel1.Text = "Lv=" + String.Format("{0:N3}", CaSDKObj.Lv) + ",sx=" + String.Format("{0:N3}", CaSDKObj.sx) + ",sy=" + String.Format("{0:N3}", CaSDKObj.sy) + ",X=" + String.Format("{0:N3}", CaSDKObj.X) + ",Y=" + String.Format("{0:N3}", CaSDKObj.Y) + ",Z=" + String.Format("{0:N3}", CaSDKObj.Z) + ",";
            if (checkBox_CASDK_MeasureRecord.Checked == true)
            {
                checkBox_CASDK_MeasureRecord.Tag = Convert.ToInt32(checkBox_CASDK_MeasureRecord.Tag) + 1;
                CAS200_AddData(checkBox_CASDK_MeasureRecord.Tag.ToString(), CaSDKObj.Lv, CaSDKObj.sx, CaSDKObj.sy, CaSDKObj.T, CaSDKObj.duv, CaSDKObj.X, CaSDKObj.Y, CaSDKObj.Z);
            }
            else
            { checkBox_CASDK_MeasureRecord.Tag = 0; }

            if (checkBox_CASDK_continue.Checked == true)
            {
                Stopflag = false;
                T1.Interval = Convert.ToInt32(text_delaytime.Text);
                T1.Enabled = true;
            }
            else
            {
                T1.Enabled = false;
            }
            Lockedflag = false;
        }
        private void T1_Tick_1(object sender, EventArgs e)//for CA410 continue measure
        {
            if (Stopflag == true)
            {
                T1.Enabled = false;
                return;
            }
            if (Lockedflag == true) return;
            Lockedflag = true;
            CaSDKObj.CASDK_AutoMeasure();
            //text_Measure_result.Text = CaSDKObj.Lv.ToString()+ ","+ CaSDKObj.sx.ToString() + "," +CaSDKObj.sy.ToString();
            text_Measure_result.Text = String.Format("{0:N3}", CaSDKObj.Lv) + "," + String.Format("{0:N3}", CaSDKObj.sx) + "," + String.Format("{0:N3}", CaSDKObj.sy) + "," + String.Format("{0:N3}", CaSDKObj.X) + "," + String.Format("{0:N3}", CaSDKObj.Z) + ",";
            toolStripStatusLabel1.Text = "Lv=" + String.Format("{0:N5}", CaSDKObj.Lv) + ",sx=" + String.Format("{0:N5}", CaSDKObj.sx) + ",sy=" + String.Format("{0:N5}", CaSDKObj.sy) + ",T=" + String.Format("{0:N1}", CaSDKObj.T) + ",X=" + String.Format("{0:N5}", CaSDKObj.X) + ",Y=" + String.Format("{0:N5}", CaSDKObj.Y) + ",Z=" + String.Format("{0:N5}", CaSDKObj.Z) + ",";

            Lockedflag = false;

        }
        private void Btn_measure2_Click(object sender, EventArgs e)
        {
            Stopflag = true;

            Lockedflag = false;
        }
        //gamma measure part from 1 to 100 or 100 to 1
        private void Gamma_measure(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            int delaytime;
            int Rrate = 0, Grate = 0, Brate = 0;
            int Scandirection = 1, startindex = 0, endindex = 0;
            int[] Measure_level = new int[256];
            int MeasureNum = 255, temlevel, measurestep;

            // 确认color 模式，根据颜色选项
            if (radioButton_W.Checked == true) { Rrate = 1; Grate = 1; Brate = 1; }
            if (radioButton_R.Checked == true) { Rrate = 1; Grate = 0; Brate = 0; }
            if (radioButton_G.Checked == true) { Rrate = 0; Grate = 1; Brate = 0; }
            if (radioButton_B.Checked == true) { Rrate = 0; Grate = 0; Brate = 1; }

            // 确认测试step，从 comBox_Slect 获取
            SelId = comBox_Slect.SelectedIndex;
            switch (comBox_Slect.SelectedIndex)
            {
                case 0:         //只测试IC bonding   
                    {
                        MeasureNum = ICGT.NodeEffetNum;
                        for (int i = 0; i < MeasureNum; i++)
                        { Measure_level[i] = NodePos_A[i]; }
                    }
                    break;
                case 1:       //  1 -step
                case 2:       //  2 -step
                case 3:       //  4 -step
                case 4:       //  8 -step
                case 5:       //  16 -step
                case 6:       //  32 -step
                case 7:       //  64 -step
                    {
                        measurestep = (Int32)Math.Pow(2, SelId - 1);
                        MeasureNum = 256 / measurestep;
                        if (256 % measurestep == 0) MeasureNum = MeasureNum + 1;
                        if (measurestep == 1) MeasureNum = 256;
                        for (int i = 0; i < MeasureNum; i++)
                        {
                            temlevel = i * measurestep;
                            if (temlevel < 256) { Measure_level[i] = temlevel; }
                            else { Measure_level[i] = 255; }
                        }
                    }
                    break;
                case 9:     //暂时为实现，待完善  
                    {
                        // Scandirection = -1;
                        Stopflag = false;
                    }
                    break;
            }
            Btn_measure2.BackColor = Color.Green;
            Stopflag = false;

            // 确认扫描方向从0-255 还是255-0
            switch (btnTmp.Text)// 确认 扫面方向从0-255 还是255-0
            {
                case "0-255":       //    2
                    {
                        Scandirection = 1;
                        startindex = 0;
                        endindex = MeasureNum;
                    }
                    break;
                case "255-0":         // 1
                    {
                        Scandirection = -1;
                        startindex = MeasureNum - 1;
                        endindex = 0;
                    }
                    break;
            }
            try
            {
                // 量测255亮度与0灰阶亮度，为归一化做准备
                nowgray = 255;
                //  Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate);

                Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate, Picpath);// 灰阶测试
                //Pattern_Write(ICGT.ICName ,nowgray* Rrate, nowgray* Grate, nowgray* Brate, true);
                Thread.Sleep(2000);
                CaSDKObj.CASDK_AutoMeasure();
                Grmaxlum = CaSDKObj.Lv;

                nowgray = 0;
                //Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate);
                Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate, Picpath);// 灰阶测试
                // Pattern_Write(ICGT.ICName, nowgray * Rrate, nowgray * Grate, nowgray * Brate, false );
                Thread.Sleep(1500);
                CaSDKObj.CASDK_AutoMeasure();
                Grminlum = CaSDKObj.Lv;
                step = 16;
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }

            if (Grmaxlum > Grminlum)//判断255 亮度与0亮度是否正常，如果正常则归一化，及测试灰阶
            {
                CAS200_dataGridView.Tag = "1";
                CAS200_dataGridView.Visible = true;
                CAS200_dataGridView.ClearSelection();
                nowgray = 0;
                Btn_measure_0_255.Tag = nowgray.ToString();
                measure_Num = 0;
                // T3_measure.Interval = Convert.ToInt16(text_delaytime.Text);
                //  T3_measure.Enabled = true;

                GmapW = pictureBox2.Width;
                GmapH = pictureBox2.Height;
                //Inital_Paint(formW - 290, formH - 120);
                Inital_Paint(GmapW, GmapH);
                if (checkBox_CAS200_dataHold.Checked == false) this.CAS200_dataGridView.Rows.Clear();
                for (int i = 0; i < MeasureNum; i++)
                {
                    if (Stopflag == false)
                    {
                        delaytime = Convert.ToInt32(text_delaytime.Text);
                        nowgray = Measure_level[startindex + i * Scandirection];
                        measure_Num = measure_Num + 1;
                        numPattern_W.Text = nowgray.ToString();
                        try
                        {
                            //Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate);

                            Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate, Picpath);// 灰阶测试
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                            return;
                        }

                        // Pattern_Write(ICGT.ICName, temlevel * Rrate, temlevel * Grate, temlevel * Brate, false);
                        Thread.Sleep(delaytime);

                        CaSDKObj.CASDK_AutoMeasure();
                        nowlum = CaSDKObj.Lv;
                        GC_Lv[measure_Num] = (nowlum - Grminlum) / (Grmaxlum - Grminlum);
                        GC_gray[measure_Num] = nowgray;
                        CAS200_AddData(nowgray.ToString(), nowlum, CaSDKObj.sx, CaSDKObj.sy, CaSDKObj.T, CaSDKObj.duv, CaSDKObj.X, CaSDKObj.Y, CaSDKObj.Z);
                        GC_gray[0] = i + 1;
                        // i = i + 4;  
                        Delay(1);
                        Update_Paint();
                    }
                    else
                    { i = 256; }
                }

            }

            Btn_measure2.BackColor = Color.DarkRed;

        }

        //gamma measure part from 1 to 100 or 100 to 1
        private void DIY_Gamma_measure(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            int delaytime;

            if (SelId == 8)
            {
                int Sacndirection = 1, startindex = 0, endindex = 0;
                int[] Measure_level = new int[256];
                int MeasureNum = 255, temlevel;
                SelId = comBox_Slect.SelectedIndex;

                Btn_measure2.BackColor = Color.Green;
                Stopflag = false;

                Sacndirection = 1;
                startindex = 0;
                endindex = MeasureNum;

                for (int i = 0; i < MeasureNum; i++)
                {
                    if (Stopflag == false)
                    {
                        delaytime = Convert.ToInt32(text_delaytime.Text);

                        temlevel = Measure_level[startindex + i * Sacndirection];
                        measure_Num = measure_Num + 1;
                        Pattern_Write(ICGT.ICName, temlevel, temlevel, temlevel, false);
                        Thread.Sleep(delaytime);

                        CaSDKObj.CASDK_AutoMeasure();
                        nowlum = CaSDKObj.Lv;
                        GC_Lv[measure_Num] = (nowlum - Grminlum) / (Grmaxlum - Grminlum);
                        GC_gray[measure_Num] = temlevel;

                        CAS200_AddData(temlevel.ToString(), nowlum, CaSDKObj.sx, CaSDKObj.sy, CaSDKObj.T, CaSDKObj.duv, CaSDKObj.X, CaSDKObj.Y, CaSDKObj.Z);
                        GC_gray[0] = i + 1;

                        Update_Paint();
                    }
                    else
                    { i = 256; }
                }



                Btn_measure2.BackColor = Color.DarkRed;

            }

        }

        private void T3_measure_Tick(object sender, EventArgs e)
        {
            double nowlum;
            int newgray, oldgray;
            T3_measure.Enabled = false;
            if (Stopflag == false)
            {                // nowgray = i;
                //Btn_measure.Tag
                oldgray = nowgray;
                newgray = nowgray;
                CaSDKObj.CASDK_AutoMeasure();
                nowlum = CaSDKObj.Lv;
                GC_Lv[measure_Num] = (nowlum - Grminlum) / (Grmaxlum - Grminlum);
                GC_gray[measure_Num] = oldgray;
                GC_gray[0] = measure_Num;
                CAS200_AddData(oldgray.ToString(), CaSDKObj.Lv, CaSDKObj.sx, CaSDKObj.sy, CaSDKObj.T, CaSDKObj.duv, CaSDKObj.X, CaSDKObj.Y, CaSDKObj.Z);
                Update_Paint();
                //Delay(1);
                if ((newgray < 255) && (nowgray + step >= 255))
                { newgray = 255; }
                else
                { newgray = newgray + step; }


                if (newgray <= 255)
                {

                    Pattern_Write(ICGT.ICName, newgray, newgray, newgray, false);
                    //  Pattern_Write(newgray, newgray, newgray);
                    //Application.DoEvents();
                    measure_Num = measure_Num + 1;
                    nowgray = newgray;
                    T3_measure.Enabled = true;
                }
                else
                {
                    T3_measure.Enabled = false;
                }
                //Thread.Sleep(1000);
            }
            else
            {
                T3_measure.Enabled = false;
            }

        }

        public void CAS200_AddnewTitle(string col_0, string col_1, string col_2, string col_3)
        {
            DataGridViewRow Row1 = new DataGridViewRow();
            int Row_Accum = CAS200_dataGridView.Rows.Count;
            CAS200_dataGridView.Rows[Row_Accum].Cells[0].Value = col_0; // Row_Accum + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            CAS200_dataGridView.Rows[Row_Accum].Cells[1].Value = col_1;
            CAS200_dataGridView.Rows[Row_Accum].Cells[2].Value = col_2;
            CAS200_dataGridView.Rows[Row_Accum].Cells[3].Value = col_3;
        }

        public void CAS200_AddData(string Gray_info, double Dgv_lum, double Dgv_x, double Dgv_y, double Dgv_T, double Dgv_uv, double Dgv_X, double Dgv_Y, double Dgv_Z)
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();
            Row_Accum = CAS200_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                // Current_Index = this.CAS200_dataGridView.SelectedCells[0].RowIndex;
                Current_Index = Row_Accum - 1;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.CAS200_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.CAS200_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.CAS200_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.CAS200_dataGridView.Rows.Add(Row1);
            }
            CAS200_dataGridView.Rows[Row_Accum].Cells[0].Value = Gray_info; // Row_Accum + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            CAS200_dataGridView.Rows[Row_Accum].Cells[1].Value = Dgv_lum.ToString("#0.0000");
            CAS200_dataGridView.Rows[Row_Accum].Cells[2].Value = Dgv_x.ToString("#0.0000");
            CAS200_dataGridView.Rows[Row_Accum].Cells[3].Value = Dgv_y.ToString("#0.0000");
            CAS200_dataGridView.Rows[Row_Accum].Cells[4].Value = Dgv_T.ToString("#0.0000");
            CAS200_dataGridView.Rows[Row_Accum].Cells[5].Value = Dgv_uv.ToString("#0.0000");
            CAS200_dataGridView.Rows[Row_Accum].Cells[6].Value = Dgv_X.ToString("#0.0000");
            CAS200_dataGridView.Rows[Row_Accum].Cells[7].Value = Dgv_Y.ToString("#0.0000");
            CAS200_dataGridView.Rows[Row_Accum].Cells[8].Value = Dgv_Z.ToString("#0.0000");
        }


        public void Delayx100ms(int mm)
        {
            mm = mm * 100;
            DateTime current = DateTime.Now;

            while ((Stopflag == false) && (current.AddMilliseconds(mm) > DateTime.Now))
            {
                Application.DoEvents();
                Thread.Sleep(100);
            }
            return;
        }

        public void Delay(int mm)
        {
            DateTime current = DateTime.Now;

            while (current.AddMilliseconds(mm) > DateTime.Now)
            {
                Application.DoEvents();
            }
            return;
        }
        #endregion/切图单元/切图单元=======LCD cfg function:OLED_Show_Click====OLED显示=================

        #region //自动调试 gamma

        int Nowindex = 0; //记录当前调试gamam index
        int flag_Lv = 0, flag_sx = 0, flag_sy = 0;
        int TuneLoopRecord;
        double temdate;
        int nowgray = 0;
        // double Target_sx, Target_sy, Target_sz, Max_X, Max_Y, Max_Z;
        CASDataType GrMindata = new CASDataType();
        CASDataType GrMaxTarget = new CASDataType();
        /*
        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            int temindex = Convert.ToInt32(text_scriptSend.Tag);
            ScriptSavestring[temindex] = text_scriptSend.Text;// 保存当前文本到string   text_scriptSend.Text = loadScriptFromfile(of.FileName);
            text_scriptSend.Text = ScriptSavestring[tabControl2.SelectedIndex];// 保存当前文本到string
            text_scriptSend.Tag = tabControl2.SelectedIndex.ToString();
            // MessageBox.Show (tabControl2.SelectedIndex.ToString ());
            //ScriptSavestring
        }
        */

        private void btnReload_Demura_File_Click(object sender, EventArgs e)
        {

        }

        private void BIN_load_path(object sender, KeyEventArgs e)
        {

        }

        private void button9_Click(object sender, EventArgs e)
        {

            FolderBrowserDialog fldb = new FolderBrowserDialog();
            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件.");
                return;
            }
            string path = fldb.SelectedPath;

            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            listBox3_Demura_File.Items.Clear();
            string s = null;
            DirectoryInfo d = new DirectoryInfo(path);
            FileInfo[] Files = d.GetFiles("*.*");//*.hex|
            // List<string> lstr = new List<string>();

            foreach (FileInfo file in Files)
            {
                s = file.Name.ToLower();
                if (s.EndsWith(".hex") || s.EndsWith(".dsc") || s.EndsWith(".bin"))
                {
                    listBox3_Demura_File.Items.Add(s);
                }
            }
            textBox5.Text = path;
        }

        private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                string FileName = textBox5.Text + '\\' + listBox3_Demura_File.SelectedItem.ToString();
                //int result = SendDemura_fromfile(FileName);

                int result = GenDemura_fromfile("02", "540", "2C", "3C", FileName);
                // if  (SendDemura_fromfile(FileName)==0) MessageBox.Show("加载", "错误");
                //------------------------------------------
                label_flash.Text += "设定 Demura Flag \r\n";
            }
            catch
            {
                MessageBox.Show("请选择文件夹", "错误");
            }
        }


        public int GenDemura_fromfile(string packtype, string packsize, string Addr_first, string Addr_second, string BinFilePath)
        {
            Int32 m_txlen = 0;
            Int32 Once_txlen = 0;
            Int32 File_Length, File_Length_tep;
            bool tx_en = true;
            byte[] TemFileContent = new byte[1024 * 100];
            char[] Acsii_array = new char[2];
            Int32 div = 0;
            div = Convert.ToInt32(packsize); //packsize 必须是偶数           
            //div = div * 3; 若此行注释掉packsize则必须为6的倍数
            Int32 ByteReaded = 0x00;
            try
            {
                // string FileName = textBox5.Text + '\\' + listBox3_Demura_File.SelectedItem.ToString();
                string FileName = BinFilePath;
                FileStream aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                File_Length = Convert.ToInt32(aFile.Length);
                if (Convert.ToInt32(aFile.Length % div) > 0)
                {
                }
                File_Length_tep = File_Length;
                //------------------------------------------
                label_flash.Text += "设定 Demura Flag \r\n";
                /*
                 * 下位机如下：
                 else if ((USB_ReceivedCount==12)&&(USB_Rx_Buffer[0]==GEN_FLAG)&&(USB_Rx_Buffer[6]==0x5a)&&(USB_Rx_Buffer[7]==0x5a))
			         gen demura cmd，next 将开始发送demura bin 档 ;bin档发送格式[0]=6A(ID),[1]=packnum,long(high8bit),[2]=packnumlow,[3]=addr,[4]=realy[0]
				Demura_START_FLAG=4;  //与其他区别
				USB_Rx_Demura=0;
				DemuraIctype=USB_Rx_Buffer[1]; //00-没有SSD addr,01=代表只有1个addr,第二笔不加addr;02=1st 一个adrr，2nd 1个Addr
				DemuraSize_H8=USB_Rx_Buffer[2]; //每笔数据分频量高8位		
				DemuraSize_L8=USB_Rx_Buffer[3];//每笔数据分频量低8位
				DemuraAddr_1st=USB_Rx_Buffer[4]; //第一笔的地址	
				DemuraAddr_2nd=USB_Rx_Buffer[5];//第二笔的地址				
				USB_Rx_Demura_Total_Num=(USB_Rx_Buffer[8]<<24)+(USB_Rx_Buffer[9]<<16)+(USB_Rx_Buffer[10]<<8)+USB_Rx_Buffer[11];
			   			
                 */

                try
                { //Demura 告诉下位机Demura数据搬运开始
                    TemFileContent[0] = 0xB5; //user 下位机HFGEN_demura
                                              // TemFileContent[1] = 0x02; //2个不同地址第一笔  1st-2C,2nd=3C

                    TemFileContent[1] = Convert.ToByte(packtype, 16);//packtype 00=下位机不加地址，01=下位机只给第一笔添加地址，02=下位机给所有笔加地址
                    TemFileContent[2] = (byte)((div & 0xFF00) >> 8);
                    TemFileContent[3] = (byte)((div & 0xFF));
                    TemFileContent[4] = Convert.ToByte(Addr_first, 16);
                    TemFileContent[5] = Convert.ToByte(Addr_second, 16);
                    TemFileContent[6] = 0x5a; //password
                    TemFileContent[7] = 0x5a;//password
                    TemFileContent[8] = Convert.ToByte(File_Length >> 24);
                    TemFileContent[9] = Convert.ToByte((File_Length >> 16) & 0xff);
                    TemFileContent[10] = Convert.ToByte((File_Length >> 8) & 0xff);
                    TemFileContent[11] = Convert.ToByte(File_Length & 0xff);
                    frmHelp.comPort.Write(TemFileContent, 0, 12);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    tx_en = false;
                    return 1;
                }
                //------------------------------------------
                while (tx_en)
                {
                    if (File_Length_tep > (File_Length % div))
                    {
                        Once_txlen = div;
                    }
                    else  //最后一笔
                    {
                        Once_txlen = Convert.ToInt32(aFile.Length % div);
                        tx_en = false;
                    }
                    aFile.Seek(0 + m_txlen, SeekOrigin.Begin);    //跳转
                    ByteReaded = aFile.Read(TemFileContent, 0, Once_txlen); // 
                    ////增加数据反序排列 rgb->bgr, 之所以这样写，是因为2KS 底板会把bmp数据由rgb转为bgr送至DDIC，2次翻转负负得正
                    //byte buf;
                    //if (chk2832DMR.Checked)  //若选择2KS -SSD2832,则需要手动翻转数据
                    //{                        
                    //    for (int tep = 0; tep < Once_txlen; tep += 3)
                    //    {
                    //        buf = TemFileContent[tep];
                    //        TemFileContent[tep] = TemFileContent[tep + 2];
                    //        TemFileContent[tep + 2] = buf;
                    //    }
                    //}                   
                    ////-------------2次翻转负负得正----
                    try
                    {
                        frmHelp.comPort.Write(TemFileContent, 0, ByteReaded);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        tx_en = false;
                        break;
                    }
                    //tx_en = false;
                    m_txlen += ByteReaded;
                    progressBar2.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                    label_flash.Text = progressBar2.Value.ToString() + "%";
                    Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                    File_Length_tep = File_Length_tep - div;
                }
                aFile.Dispose();
                aFile.Close();

                return 1;//  "Send Demura bin ok";
            }
            catch
            {
                MessageBox.Show("请选择文件夹", "错误");
                return 0;//  "Send Demura bin fail";
            }

        }

        //保存script 脚本
        private void SavetextFile(string sFilePath, string textcontain, bool append)
        {
            StreamWriter sw = null; //文件流
            sw = new StreamWriter(sFilePath, append, Encoding.UTF8);
            int temindex = Convert.ToInt32(text_script_send_all.Tag);
            listBox_SendScript.Items[temindex] = (temindex + 1).ToString() + "-" + System.IO.Path.GetFileName(sFilePath);
            try
            {
                sw.Write(textcontain);
                sw.Dispose(); //释放资源
                sw.Close(); //关闭数据流
            }
            catch
            {
                MessageBox.Show("保存2K脚本文件 时发生错误，请再试！", "系统提示：");
            }

        }


        //加载script 脚本
        private string loadScriptFromfile(string scritptFilePath)
        {
            String totalstr = "";
            if (File.Exists(scritptFilePath))
            {
                //读取文本信息
                FileStream fs = new FileStream(scritptFilePath, FileMode.Open, FileAccess.Read);
                //StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("UTF8"));//GBK
                StreamReader streamReader = new StreamReader(fs, Encoding.UTF8);//GBK
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                totalstr = streamReader.ReadToEnd();

                streamReader.Dispose();
                streamReader.Close();
                fs.Dispose();
                fs.Close(); //关闭流
                streamReader = null;
                fs = null;
            }
            return totalstr;
        }

        private void openScriptSendToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "2K脚本文件(*.2kscript)|*.2kscript;*.mcr;*.txt|所有文件(*.*)|*.*";
            of.Title = "Open 2K脚本文件";
            String totalstr = "";
            if (of.ShowDialog() == DialogResult.OK)
            {
                text_script_send_all.Text = loadScriptFromfile(of.FileName);
                int temindex = Convert.ToInt32(text_script_send_all.Tag);
                listBox_SendScript.Items[temindex] = (temindex + 1).ToString() + "-" + of.SafeFileName;
            }
        }

        private void saveScriptSendToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = "2K脚本文件(*.2kscript)|*.2kscript;*.mcr;*.txt|所有文件(*.*)|*.*";
            sf.Title = "Save 2K脚本文件";
            string textstr ="";
            // string[] subline;
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);

                if (tab_Debug_File.SelectedIndex == 1)// file salect
                {
                    textstr = txt_send_cmd_all.Text;
                }
                else
                {
                    int temindex = Convert.ToInt32(text_script_send_all.Tag);
                    listBox_SendScript.Items[temindex] = (temindex + 1).ToString() + "-" + System.IO.Path.GetFileName(sf.FileName);
                    textstr = text_script_send_all.Text;
                }
                try
                {
                    sw.Write(textstr);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    //MessageBox.Show("Driver GammaCode保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("保存2K脚本文件 时发生错误，请再试！", "系统提示：");
                }

            }
        }
        private void openCFGGitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string Userpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG\\Gamma_CFG\\";
            System.Diagnostics.Process.Start("explorer.exe", Userpath);
        }
        private void TrackBar_51_Scroll(object sender, EventArgs e)
        {
            if (Lockedflag == false)
            {
                Lockedflag = true;
                int temvalue = TrackBar_51.Value;
                int Hibyte = 0, Lowbyte = 0;
                Hibyte = (temvalue & 0xff00) >> 8;
                Lowbyte = (temvalue & 0xff);
                Label_DBV_51MSG.Text = temvalue * IC51Reg.Showrate + "阶";
                numericUpDown_51Reg.Value = temvalue;
                if (IC51Reg.Parmap == "MS")
                {
                    Text_51Reg_W.Text = IC51Reg.Regname + "," + Hibyte.ToString("X2") + "," + Lowbyte.ToString("X2");
                }
                if (IC51Reg.Parmap == "LS")
                {
                    Text_51Reg_W.Text = IC51Reg.Regname + "," + Lowbyte.ToString("X2") + "," + Hibyte.ToString("X2");
                }
                if (checkBox_btn_51.Checked == true)
                {
                    SerialPort_ReadOpen();
                    Write99Comport_Script(Text_51Reg_W.Text);
                }
                // SerialPort_ReadClose();

                Lockedflag = false; //解锁
            }
        }

        private void btn_51_Click(object sender, EventArgs e)
        {
            string tempstr = Text_51Reg_W.Text;
            Write99Comport_Script(tempstr);
        }

        private void numericUpDown_Reg_ValueChanged(object sender, EventArgs e)
        {
            if (Lockedflag == false)
            {
                Lockedflag = true;
                int temvalue = (int)numericUpDown_51Reg.Value;
                int Hibyte = 0, Lowbyte = 0;
                Hibyte = (temvalue & 0xff00) >> 8;
                Lowbyte = (temvalue & 0xff);
                TrackBar_51.Value = temvalue;
                Label_DBV_51MSG.Text = temvalue * IC51Reg.Showrate + "阶";
                //numericUpDown_Reg.Value = temvalue;
                if (IC51Reg.Parmap == "MS")
                {
                    Text_51Reg_W.Text = IC51Reg.Regname + "," + Hibyte.ToString("X2") + "," + Lowbyte.ToString("X2");
                }
                if (IC51Reg.Parmap == "LS")
                {
                    Text_51Reg_W.Text = IC51Reg.Regname + "," + Lowbyte.ToString("X2") + "," + Hibyte.ToString("X2");
                }
                if (checkBox_btn_51.Checked == true)
                {
                    SerialPort_ReadOpen();
                    Write99Comport_Script(Text_51Reg_W.Text);
                }
                // SerialPort_ReadClose();
                Lockedflag = false; //解锁
            }
        }

        private void Btn_CAS200_dataClear_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                this.CAS200_dataGridView.Rows.Clear();
            }
            else {; }
        }

        private void Btn_CAS200_dataSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型

            string str = "序号,x坐标,y坐标,lv,T,uv,X,Y,Z\r\n";

            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                    for (int i = 0; i < (this.CAS200_dataGridView.Rows.Count - 1); i++)
                    {
                        str = str + this.CAS200_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                            + this.CAS200_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                            + this.CAS200_dataGridView.Rows[i].Cells[3].Value.ToString() + ","
                            + this.CAS200_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                            + this.CAS200_dataGridView.Rows[i].Cells[4].Value.ToString() + ","
                            + this.CAS200_dataGridView.Rows[i].Cells[5].Value.ToString() + ","
                            + this.CAS200_dataGridView.Rows[i].Cells[6].Value.ToString() + ","
                            + this.CAS200_dataGridView.Rows[i].Cells[7].Value.ToString() + ","
                            + this.CAS200_dataGridView.Rows[i].Cells[8].Value.ToString();
                        str = str + "\r\n";

                    }
                    sw.WriteLine(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("测试数据保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("测试数据保存时发生错误，请再试！", "系统提示：");
                }
            }

        }

        private void comBox_Slect_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void showGammaDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CAS200_dataGridView.Tag = 1;
            AGengamma_SizeChanged(sender, e);


        }

        private void hideGammaDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CAS200_dataGridView.Tag = 0;
            Btn_CAS200_dataClear.Visible = false;
            Btn_CAS200_dataSave.Visible = false;
            CAS200_dataGridView.Visible = false;
            checkBox_CAS200_dataHold.Visible = false;
            AGengamma_SizeChanged(sender, e);
        }
        //根据选项确认bist  开关
        private void checkBox_Pattern_Bist_CheckedChanged(object sender, EventArgs e)
        {

            // string cmdcode = "";
            if (checkBox_Pattern_Bist.Checked == true) //bist mode
            {
                switch (ICGT.ICName)
                {
                    case "ICNA3511":         //3511 支持bist,切RGB 配比画面DSIW,9F,01;DSIW,C6,03;
                        {
                            WriteComport("99,1E,9F,01"); //3511 下9f,01
                            WriteComport("99,1E,C6,03"); //3511 下C6,03                         
                        }
                        break; //BL
                    default:
                        break; //BL
                }
            }
            else //非bist mode
            {
                switch (ICGT.ICName)
                {
                    case "ICNA3511":         //3511 支持bist,切RGB 配比画面DSIW,9F,01;DSIW,C6,03;
                        {
                            WriteComport("99,1E,9F,01"); //3511 下9f,01
                            WriteComport("99,1E,C6,00"); //3511 下C6,00 //关闭bist     
                        }
                        break; //BL
                    default:
                        break; //BL
                }
            }
        }
        // 根据选项确定Autogamma /automeasure 是否用图片切图
        // public   picpath as string
        private void checkBox_Pattern_Pic_Click(object sender, EventArgs e)
        {
            if (checkBox_Pattern_Pic.Checked == true) //bist mode
            {
                Picpath = textBox2.Text + "\\";
            }
            else
            {
                Picpath = "";
            }
        }

        //calc target lv,x,y and limit Lv,x,y
        private void Cacla_Target(double in_GammaRate, CASDataType in_min, CASDataType in_max, int in_maxloop)
        {
            //int m, n;
            //Target_XYZ[0] = new double[ICGT.NodeNum];
            //Target_XYZ[1] = new double[ICGT.NodeNum];
            //Target_XYZ[2] = new double[ICGT.NodeNum];
            //Target_XYZ[3] = new double[ICGT.NodeNum];

            double Max_Total;
            Target_XYZ = new double[4, ICGT.NodeNum];
            Nodetarget = new NodeTargetType[ICGT.NodeNum];
            Max_Total = in_max.X + in_max.Y + in_max.Z;
            for (int i = 0; i < ICGT.NodeEffetNum; i++)
            {
                temdate = NodePos_A[i];
                temdate = Math.Pow((temdate / 255), in_GammaRate);
                // Target_XYZ[0, i] = temdate * (in_max.X - in_min.X) + in_min.X;
                Target_XYZ[1, i] = temdate * (in_max.Y - in_min.Y) + in_min.Y;
                // Target_XYZ[2, i] = temdate * (in_max.Z - in_min.Z) + in_min.Z;

                Target_XYZ[0, i] = Target_XYZ[1, i] * in_max.sx / in_max.sy; // 强制色坐标法
                Target_XYZ[2, i] = Target_XYZ[1, i] * (1 - in_max.sx - in_max.sy) / in_max.sy;// 强制色坐标法

                Target_XYZ[3, i] = temdate * (in_max.X + in_max.Y + in_max.Z - in_min.X - in_min.Y - in_min.Z) + in_min.X + in_min.Y + in_min.Z;
                GrayTune_loopnum[i] = in_maxloop;

                Nodetarget[i].sx = in_max.sx;
                Nodetarget[i].sy = in_max.sy;
                Nodetarget[i].gamma_rate = in_GammaRate;

            }
            //update 更新自定义x修正，如果有的话
            //ICGT.GGN_Target  = *,RATE/LV,2.2,450,0.30,0.32;3,2.4,0.30,0.32; 
            string[] subtarget;
            string[] subsubtarget;
            int corregray = 0;
            int correindex = 0;
            if (ICGT.GGN_Target != "") //不等空
            {
                subtarget = ICGT.GGN_Target.Split(';');
                for (int i = 1; i < subtarget.Length; i++)// index 从 1 开始；默认 0wei *,2,2,450,x,y 全部绑点； 后面 为个别nodeindex,RATE/LV/PER,Ycorr,x,y
                {
                    if (subtarget[i] != "") //不等空
                    {
                        subsubtarget = subtarget[i].Split(',');
                        corregray = Convert.ToInt32(subsubtarget[0]);
                        correindex = -1;
                        for (int gindex = 0; gindex < ICGT.NodeEffetNum; gindex++) //search gray loc index
                        {
                            temdate = NodePos_A[gindex];
                            if (temdate == corregray)
                            {
                                correindex = gindex;
                                break;
                                //    correindex = Convert.ToInt32(subsubtarget[0]) - 1;
                            }

                        }
                        if (correindex >= 0)
                        {
                            if (subsubtarget[1].ToUpper() == "RATE")//gamma 指数修正eg：index,rate,2.4,x,y
                            {
                                temdate = NodePos_A[correindex];
                                temdate = Math.Pow((temdate / 255), Convert.ToDouble(subsubtarget[2]));
                                Target_XYZ[1, correindex] = temdate * (in_max.Y - in_min.Y) + in_min.Y;
                                Nodetarget[correindex].gamma_rate = in_GammaRate;
                            }
                            else if (subsubtarget[1].ToUpper() == "LV")//gamma 指数修正eg：index,lv,500,x,y  绝对亮度
                            {
                                //correindex = Convert.ToInt32(subsubtarget[0]) - 1;
                                Target_XYZ[1, correindex] = Convert.ToDouble(subsubtarget[2]);
                            }
                            Target_XYZ[0, correindex] = Target_XYZ[1, correindex] * Convert.ToDouble(subsubtarget[3]) / Convert.ToDouble(subsubtarget[4]);
                            Target_XYZ[2, correindex] = Target_XYZ[1, correindex] * (1 - Convert.ToDouble(subsubtarget[3]) - Convert.ToDouble(subsubtarget[4])) / Convert.ToDouble(subsubtarget[4]);

                            Nodetarget[correindex].sx = Convert.ToDouble(subsubtarget[3]);
                            Nodetarget[correindex].sy = Convert.ToDouble(subsubtarget[4]);
                        }

                    }
                }
            }
            //=============Calc Target limit start =========================================
            //double[][] Target_Limit = new double[5][]; //记录nit,rate,lv_limit,x_limit,y_limit
            //string temlimit = "0.1,RATE/PER/Lv,0.001,0.01,0.01;0.5,PER/Lv,0.001,0.002,0.002;10,RATE/PER/Lv,0.001,0.002,0.002;10000,RATE/PER/Lv,0.001,0.002,0.002;";
            string temlimit = "0.03,PER,0.1,0.1,0.1;0.1,PER,0.1,0.05,0.05;0.5,PER,0.01,0.005,0.005;10,PER,0.01,0.002,0.002;10000,PER,0.005,0.002,0.002;";
            if ((ICGT.GGN_TargetLimit != "") & ICGT.GGN_TargetLimit != null) temlimit = ICGT.GGN_TargetLimit;//如果cfg配置文件有自定义限制按照配置文件，如果没有按照默认；
            subtarget = temlimit.Split(';');
            Target_Limit = new double[5, subtarget.Length + 1];
            int limitnodenum = subtarget.Length;//记录亮度限制段数
            for (int i = 0; i < subtarget.Length; i++)
            {
                if (subtarget[i] != "") //不等空
                {
                    subsubtarget = subtarget[i].Split(',');
                    Target_Limit[0, i] = Convert.ToDouble(subsubtarget[0]);
                    Target_Limit[2, i] = Convert.ToDouble(subsubtarget[2]);
                    Target_Limit[3, i] = Convert.ToDouble(subsubtarget[3]);
                    Target_Limit[4, i] = Convert.ToDouble(subsubtarget[4]);
                    if (subsubtarget[1].ToUpper() == "LV") Target_Limit[1, i] = 0;
                    else if (subsubtarget[1].ToUpper() == "RATE") Target_Limit[1, i] = 1;
                    else if (subsubtarget[1].ToUpper() == "PER") Target_Limit[1, i] = 2;
                }
            }

            for (int i = 0; i < ICGT.NodeEffetNum; i++)
            {
                for (int j = 0; j < limitnodenum; j++)
                {
                    if ((Target_XYZ[1, i] > 0) && (Target_XYZ[1, i] <= Target_Limit[0, j])) //目标亮度小于限定亮度则在范围内
                    {

                        if (Target_Limit[1, j] == 0)// 限定格式为绝对亮度
                        {
                            Nodetarget[i].UpLv = Target_XYZ[1, i] + Target_Limit[2, j];
                            Nodetarget[i].LowLv = Target_XYZ[1, i] - Target_Limit[2, j];
                            //Target_XYZ[4, i] = Target_XYZ[1, i] + Target_Limit[2, j];
                            //Target_XYZ[5, i] = Target_XYZ[1, i] - Target_Limit[2, j];
                        }
                        else if (Target_Limit[1, j] == 1) // 限定格式为+/- gamma rate
                        {
                            temdate = NodePos_A[i];
                            temdate = Math.Pow((temdate / 255), Nodetarget[i].gamma_rate - Target_Limit[2, j]); //
                            Nodetarget[i].UpLv = temdate * (in_max.Y - in_min.Y) + in_min.Y;
                            temdate = NodePos_A[i];
                            temdate = Math.Pow((temdate / 255), Nodetarget[i].gamma_rate + Target_Limit[2, j]);
                            Nodetarget[i].LowLv = temdate * (in_max.Y - in_min.Y) + in_min.Y;
                        }
                        else if (Target_Limit[1, j] == 2) // 限定格式为百分比
                        {
                            Nodetarget[i].UpLv = Target_XYZ[1, i] * (1 + Target_Limit[2, j]);
                            Nodetarget[i].LowLv = Target_XYZ[1, i] * (1 - Target_Limit[2, j]);
                        }
                        Nodetarget[i].Limit_sx = Target_Limit[3, j]; //+/-x_delt
                        Nodetarget[i].Limit_sy = Target_Limit[4, j]; //+/-y_delt

                        break;
                    }
                }

            }

            //=============Calc Target limit end=========================================

        }

        private void listBox_SendScript_MouseClick(object sender, MouseEventArgs e)
        {
            int temindex = Convert.ToInt32(text_script_send_all.Tag);
            ScriptSavestring[temindex] = text_script_send_all.Text;// 保存当前文本到string   text_scriptSend.Text = loadScriptFromfile(of.FileName);
            if (text_listTitle.Text != "") listBox_SendScript.Items[temindex] = text_listTitle.Text;

            text_script_send_all.Text = ScriptSavestring[listBox_SendScript.SelectedIndex];// 保存当前文本到string
            text_script_send_all.Tag = listBox_SendScript.SelectedIndex.ToString();

            btnColor_Click(8);
            switch (text_script_send_all.Tag)
            {
                case "0": 
                    textBox_Scrinp1.Text = text_script_send_all.Text;
                    break;
                case "1":
                    textBox_Scrinp2.Text = text_script_send_all.Text;
                    break;
                case "2":
                    textBox_Scrinp3.Text = text_script_send_all.Text;
                    break;
                case "3":
                    textBox_Scrinp4.Text = text_script_send_all.Text;
                    break;
                case "4":
                    textBox_Scrinp5.Text = text_script_send_all.Text;
                    break;
                case "5":
                    textBox_Scrinp6.Text = text_script_send_all.Text;
                    break;
                case "6":
                    textBox_Scrinp7.Text = text_script_send_all.Text;
                    break;
                case "7":
                    textBox_Scrinp8.Text = text_script_send_all.Text;
                    break;
                default:
                    break;
            }




        }
        private void listBox_SendScript_SelectedIndexChanged(object sender, EventArgs e)
        {
            text_listTitle.Text = Convert.ToString(listBox_SendScript.SelectedItem);
        }
        private void btn_51page_Click(object sender, EventArgs e)
        {

        }
        private void text_gamaRate_TextChanged(object sender, EventArgs e)
        {
            double temrat = GammaRat;
            if ((text_gamaRate.Text != "") && (Convert.ToDouble(text_gamaRate.Text) > 0.2))
            {
                GammaRat = Convert.ToDouble(text_gamaRate.Text);
                Inital_Paint(pictureBox2.Width, pictureBox2.Height);
                Update_Paint();
            }
            else
            {
                MessageBox.Show("Gamma rate should >0.2!");
            }
        }



        private void Btn_savelog_Click(object sender, EventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义保存的文件的类型
            //string str = "保存Gamma Code文件";
            string textstr, linestr;
            string[] subline;
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(sf.FileName + "_code.txt", false, Encoding.Default);
                textstr = text_script_send_all.Text;
                textstr = textstr.Replace("\r\n", "$");
                subline = textstr.Split('$');
                try
                {
                    for (int i = 0; i < subline.Length; i++)     //IC 初始化代码
                    {
                        linestr = subline[i];
                        sw.WriteLine(linestr);
                    }
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    //MessageBox.Show("Driver GammaCode保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Driver Gamma Code保存时发生错误，请再试！", "系统提示：");
                }


                sw = new StreamWriter(sf.FileName + "_Msg.log", false, Encoding.Default);
                textstr = text_gammaMsg.Text;
                textstr = textstr.Replace("\r\n", "$");
                subline = textstr.Split('$');
                try
                {
                    for (int i = 0; i < subline.Length; i++)     //IC 初始化代码
                    {
                        linestr = subline[i];
                        sw.WriteLine(linestr);
                    }
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                }
                catch
                {
                    MessageBox.Show("保存 Msglog 时发生错误，请再试！", "系统提示：");
                }
                sw = new StreamWriter(sf.FileName + "_Log.log", false, Encoding.Default);
                textstr = text_RecMsg.Text;
                textstr = textstr.Replace("\r\n", "$");
                subline = textstr.Split('$');
                try
                {
                    for (int i = 0; i < subline.Length; i++)     //IC 初始化代码
                    {
                        linestr = subline[i];
                        sw.WriteLine(linestr);
                    }
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    //MessageBox.Show("Driver GammaCode保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("保存 log 时发生错误，请再试！", "系统提示：");
                }

            }
        }
        private void treeView_GammaGroupN_AfterCheck(object sender, TreeViewEventArgs e)
        {
            //TreeNode subnode = sender;

            if ((e.Action != TreeViewAction.Unknown) || (e.Node != null))
            {
                if (e.Node.Tag.ToString().Substring(0, 1) == "$") //是父node  
                {
                    foreach (TreeNode tn in e.Node.Nodes)
                    {
                        tn.Checked = e.Node.Checked;

                    }
                }
            }
        }


        private void treeView_GammaGroupN_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {

            treeView_GammaGroupN_AfterSelectIndex();
        }


        private void treeView_GammaGroupN_AfterSelect(object sender, TreeViewEventArgs e)
        {

            treeView_GammaGroupN_AfterSelectIndex();
        }

        private void treeView_GammaGroupN_AfterSelectIndex()
        {
            if (treeView_GammaGroupN.SelectedNode == null) //是父node 
                return;

            int nodeindex = treeView_GammaGroupN.SelectedNode.Index;
            string nodetag = treeView_GammaGroupN.SelectedNode.Tag.ToString();
            if (nodetag.Substring(0, 1) == "$") //是父node 
                return;
            foreach (TreeNode tn in treeView_GammaGroupN.Nodes)
            {
                tn.Checked = false;
                foreach (TreeNode subtn in tn.Nodes)
                {
                    subtn.Checked = false;
                }
            }
            treeView_GammaGroupN.SelectedNode.Checked = true;
            GetgammCfg(1, nodetag);
            //ShowArray();

            AddScriptShow(text_script_send_all, ScriptDebugflag, ICGT.GGN_ClickCode);
            //ICGT.GGN_Target  = *,RATE/LV,2.2,450,0.30,0.32;3,2.4,0.30,0.32;
            if (ICGT.GGN_Target != "") //不等空
            {
                string[] subtarget = ICGT.GGN_Target.Split(';');
                string[] subsubtarget = subtarget[0].Split(',');
                if (subsubtarget[0] == "*")
                {

                    text_gamaRate.Tag = "*";
                    // subsubtarget = subtarget[1].Split(',');
                    text_gamaRate.Text = subsubtarget[1];
                    text_255targe_lv.Text = subsubtarget[2];
                    text_255targe_sx.Text = subsubtarget[3];
                    text_255targe_sy.Text = subsubtarget[4];
                }
            }
            //text_DebugSend.Text = TransCode(text_RecMsg.Text);
            //  WriteComport(text_DebugSend.Text);
            try
            {
                Stopflag = false;
                IClosing = true; //关闭自动recivew
                SerialPort_ReadOpen();
                string ss = Write99Comport_Script(text_script_send_all.Text);
                SerialPort_ReadClose();
            }
            catch (Exception emsg)
            {
                if (MessageBox.Show(Err_report + "\r\n" + emsg.Message + "\r\n continue run?", "Error Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    Stopflag = true;
                    return;
                }
                // MessageBox.Show(emsg.Message, "系统提示：");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            text_scriptRec.Text = ""; text_RecMsg.Text = ""; text_SendMsg.Text = "";
            System.Media.SystemSounds.Hand.Play();

        }



        private void checkBox_Sendscript_wordwrap_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_Sendscript_wordwrap.Checked == true)
            {
                text_script_send_all.WordWrap = true;
            }
            else
            {
                text_script_send_all.WordWrap = false;
            }
        }
        private void checkBox_Recscript_wordwrap_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_Recscript_wordwrap.Checked == true)
            {
                text_scriptRec.WordWrap = true;
            }
            else
            {
                text_scriptRec.WordWrap = false;
            }
        }
        private void button6_Click(object sender, EventArgs e)
        {

            frmHelp.LCD_HWRST();
            AddMsgShow(text_scriptRec, ScriptDebugflag, "HWRST");
            //text_scriptRec.Text += StrArry[i] + "\r\n"; LCD_cfgInital


        }

        private void button7_Click(object sender, EventArgs e)
        {

            frmHelp.LCD_cfgInital();
            AddMsgShow(text_scriptRec, ScriptDebugflag, "LCM_INITAL");
            //text_scriptRec.Text += StrArry[i] + "\r\n"; LCD_cfgInital

        }

        private void text_listTitle_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnscriptPath_Click(object sender, EventArgs e)
        {
            string Userpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG";
            string defualtinfPath = Userpath + "\\Lastlog.inf";
            bool result;

            string tempath = ReadIni("Lastlog", "2KscriptPath", defualtinfPath);
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            fldb.ShowNewFolderButton = false;
            if (Directory.Exists(tempath))
            {
                //fldb.RootFolder = new DirectoryInfo(textBox_FilescriptPath.Text);
                //fldb.RootFolder(textBox_FilescriptPath.Text);
                fldb.SelectedPath = tempath;
            }
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件.");
                return;
            }
            string path = fldb.SelectedPath;

            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            listBox_FilescriptPath.Items.Clear();
            string s = null;
            DirectoryInfo d = new DirectoryInfo(path);
            FileInfo[] Files = d.GetFiles("*.*");//*.hex|
            // List<string> lstr = new List<string>();
            int listcount = 0;
            foreach (FileInfo file in Files)
            {
                s = file.Name.ToLower();
                if (s.EndsWith(".txt") || s.EndsWith(".mcr") || s.EndsWith(".2kscript"))
                {
                    listBox_FilescriptPath.Items.Add(s);
                    ScriptLoadFilestring[listcount] = loadScriptFromfile(path + "\\" + file.Name);
                    //listBox_FilescriptPath.Items[listcount].Tag

                    listcount = listcount + 1;
                }
            }
            result = WritePrivateProfileString("Lastlog", "2KscriptPath", path, defualtinfPath);
            listBox_FilescriptPath.Tag = "0";
            txt_send_cmd_all.Text = ScriptLoadFilestring[0];
            textBox_FilescriptPath.Text = path;

        }



        private void listBox_FilescriptPath_Click(object sender, EventArgs e)
        {
            //if ((listBox_FilescriptPath.SelectedItem != null) & (textBox_FilescriptPath.Text != ""))
            //{
            //    //string FileName = textBox_FilescriptPath.Text + '\\' + listBox_FilescriptPath.SelectedItem.ToString();
            //    //int result = SendDemura_fromfile(FileName);
            //    // text_scriptSend2.Text = loadScriptFromfile(FileName);
            //    //   int id = listBox_FilescriptPath.SelectedItem;
            //    //  text_scriptSend2.Text = ScriptLoadFilestring[id];

            //    int temindex = Convert.ToInt32(text_scriptSend2.Tag);
            //    ScriptLoadFilestring[temindex] = text_scriptSend2.Text;// 保存当前文本到string   text_scriptSend.Text = loadScriptFromfile(of.FileName);
            //                                                           // if (text_listTitle.Text != "") listBox_SendScript.Items[temindex] = text_listTitle.Text;

            //    text_scriptSend2.Text = ScriptLoadFilestring[listBox_FilescriptPath.SelectedIndex];// 保存当前文本到string
            //    text_scriptSend2.Tag = listBox_FilescriptPath.SelectedIndex.ToString();
            //}
        }
        private void listBox_FilescriptPath_DoubleClick(object sender, EventArgs e)
        {
            //  int result = GenDemura_fromfile("02", "540", "2C", "3C", FileName);
            try
            {
                Stopflag = false;
                IClosing = true; //关闭自动recivew
                SerialPort_ReadOpen();
                //string ss = Write99Comport_muilt(text_scriptSend.Text);
                string ss = Write99Comport_Script(txt_send_cmd_all.Text);
                //text_SendMsg.Text += ss;
            }
            catch (Exception emsg)
            {
                SerialPort_ReadClose();
                if (MessageBox.Show(Err_report + "\r\n" + emsg.Message + "\r\n continue run?", "Error Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    Stopflag = true;
                    goto Err_End;
                }
                // MessageBox.Show(emsg.Message, "系统提示：");
            }
            SerialPort_ReadClose();

        Err_End:
            return;
        }



        private void tabControl4_MouseClick(object sender, MouseEventArgs e)
        {
            if (tab_Debug_File.SelectedIndex == 1)
            {
                tab_script_page.Parent = null;
                tab_cmd_file.Parent = tab_send_control;
            }
            else
            {
                tab_script_page.Parent = tab_send_control;
                tab_cmd_file.Parent = null;
            }
        }

        private void btn_FilescriptPath_Save_Click(object sender, EventArgs e)
        {
            if ((listBox_FilescriptPath.SelectedItem != null) & (textBox_FilescriptPath.Text != ""))
            {
                string path = textBox_FilescriptPath.Text;
                string filepath = path + "\\" + listBox_FilescriptPath.SelectedItem.ToString();
                if (filepath == "") return; //如果没有输入文件名
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(filepath, false, Encoding.UTF8);
                try
                {
                    sw.Write(txt_send_cmd_all.Text);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                                //MessageBox.Show("Driver GammaCode保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("保存2K脚本文件 时发生错误，请再试！", "系统提示：");
                }
            }

        }

        private void openGammaLogToolStripMenuItem_Click(object sender, EventArgs e)
        {

            // Gammacodepath = Application.StartupPath + "\\HF_Autogamma\\" + DateTime.Now.ToString("yyyy-MM-dd");
            string Gammalogpath = Application.StartupPath + "\\HF_Autogamma\\" + DateTime.Now.ToString("yyyy-MM-dd");
            if (!Directory.Exists(Gammalogpath))
            {
                Gammalogpath = Application.StartupPath + "\\HF_Autogamma";
            }
            System.Diagnostics.Process.Start("explorer.exe", Gammalogpath);
        }

        private void hFGenw6AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HF_GenW_port = "6A 20"; //2KS  96端口
        }

        private void hFGenw96ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HF_GenW_port = "96 20"; //2KS  96端口
        }

        private void enPackageDebugLogToolStripMenuItem_Click(object sender, EventArgs e)
        {

            SendDebugflag = true; RecDebugflag = true;
        }

        private void disableFasterWriteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FasteWflag = false;
        }


        private void disPackageDebugLogToolStripMenuItem_Click(object sender, EventArgs e)
        {

            SendDebugflag = false; RecDebugflag = false;
        }

        private void numPattern_W_KeyDown(object sender, KeyEventArgs e)
        {
            // MessageBox.Show(e.KeyCode.ToString());
            if (e.KeyCode == Keys.Enter)
            {
                PureColor_Show();
            }
        }

        //1019 new 算法：步长估算算法，根据上一步调整步长及亮度变化 ，动态估算此时步长
        Int16[] record_oldRGBstep = new Int16[3];



        double[] record_oldXYZ = new double[3];
        double[,] Rd_upstep = new double[3, 8];  //记录RGB值最接近目标值得上限0=R,1=G,2=B, 3=X,4=Y,5=Z


        double[,] Rd_lowstep = new double[3, 8];//记录RGB值最接近目标值得下限
        int ChangePicDelay = 1000;

        private void button8_Click(object sender, EventArgs e)
        {

        }

        private void T2_autogamma_Tick(object sender, EventArgs e)
        {
            double[] now_XYZ = new double[4];
            double now_sx, now_sy, now_sz;
            double[] diffXYZ = new double[3];
            Int16[] Old_RGB_A = new Int16[3];
            T2_autogamma.Enabled = false;//先暂停计时器；
            TuneLoopRecord++;

            string recordMsg = ""; ;
            string getcode = "";
            #region  //mueasure value
            try
            {
                CaSDKObj.CASDK_AutoMeasure();
                now_XYZ[1] = CaSDKObj.Lv;
                now_sx = CaSDKObj.sx;
                now_sy = CaSDKObj.sy;
                now_sz = 1 - now_sx - now_sy;

            }
            catch (Exception emsg)
            {
                MessageBox.Show(emsg.Message, "Error Message");
                Stopflag = true;
                T2_autogamma.Enabled = false;//停止计时器
                return;
            }

            now_XYZ[0] = now_sx / now_sy * now_XYZ[1];
            now_XYZ[2] = now_sz / now_sy * now_XYZ[1];
            Old_RGB_A[0] = RGB_Value_A[0][Nowindex];
            Old_RGB_A[1] = RGB_Value_A[1][Nowindex];
            Old_RGB_A[2] = RGB_Value_A[2][Nowindex];
            //--------更新记录的上下限限制--------------------
            /*

            if ((Target_XYZ[0, Nowindex] <= now_XYZ[0]) && (Target_XYZ[1, Nowindex] <= now_XYZ[1]) && (Target_XYZ[2, Nowindex] <= now_XYZ[2]))
            {
                if (Rd_upstep[0, 7] == 0) //=0 说明没有初始化
                {   //没有初始化，只要抓到比目标值大的就算上限               
                    Rd_upstep[0, 0] = Old_RGB_A[0]; Rd_upstep[0, 1] = Old_RGB_A[1]; Rd_upstep[0, 2] = Old_RGB_A[2];
                    Rd_upstep[0, 3] = now_XYZ[0]; Rd_upstep[0, 4] = now_XYZ[1]; Rd_upstep[0, 5] = now_XYZ[2];
                    Rd_upstep[0, 7] += 1;
                    MecordMsg = "update =(" + Rd_upstep[0, 7] + "," + Rd_upstep[0, 0] + "," + Rd_upstep[0, 1] + "," + Rd_upstep[0, 2] + "," + Rd_upstep[0, 3] + "," + Rd_upstep[0, 4] + "," + Rd_upstep[0, 5] + ",";
                    AddMsgShow(text_gammaMsg, GammaDebugflag, MecordMsg);
                }//已经初始化初始化，必须要更接近目标值才更新上限
                else if ((Rd_upstep[0, 3]+10 >= now_XYZ[0]) && (Rd_upstep[0, 4] + 10 >= now_XYZ[1]) && (Rd_upstep[0, 5] + 10 >= now_XYZ[2])) //新测试的比之前记录小
                {
                    if ((Rd_upstep[0, 0] >= Old_RGB_A[0]) && (Rd_upstep[0, 1] >= Old_RGB_A[1]) && (Rd_upstep[0, 2] >= Old_RGB_A[2])) //新测试的比之前记录小
                    {
                        Rd_upstep[0, 0] = Old_RGB_A[0]; Rd_upstep[0, 1] = Old_RGB_A[1]; Rd_upstep[0, 2] = Old_RGB_A[2];
                        Rd_upstep[0, 3] = now_XYZ[0]; Rd_upstep[0, 4] = now_XYZ[1]; Rd_upstep[0, 5] = now_XYZ[2];
                        Rd_upstep[0, 7] += 1;
                        MecordMsg = "update =(" + Rd_upstep[0, 7] + "," + Rd_upstep[0, 0] + "," + Rd_upstep[0, 1] + "," + Rd_upstep[0, 2] + "," + Rd_upstep[0, 3] + "," + Rd_upstep[0, 4] + "," + Rd_upstep[0, 5] + ",";
                        AddMsgShow(text_gammaMsg, GammaDebugflag, MecordMsg);
                    }
                }
            }


            if ((Target_XYZ[0, Nowindex] >= now_XYZ[0]) && (Target_XYZ[1, Nowindex] >= now_XYZ[1]) && (Target_XYZ[2, Nowindex] >= now_XYZ[2])) //新测试的比之前记录小
            {
                if (Rd_lowstep[0, 7] == 0) //=0 说明没有初始化
                {  // 没有初始化，只要抓到比目标值小的就算下限
                    Rd_lowstep[0, 0] = Old_RGB_A[0]; Rd_lowstep[0, 1] = Old_RGB_A[1]; Rd_lowstep[0, 2] = Old_RGB_A[2];
                    Rd_lowstep[0, 3] = now_XYZ[0]; Rd_lowstep[0, 4] = now_XYZ[1]; Rd_lowstep[0, 5] = now_XYZ[2];
                    Rd_lowstep[0, 7] += 1;
                    MecordMsg = "Lowdate =(" + Rd_lowstep[0, 7] + "," + Rd_lowstep[0, 0] + "," + Rd_lowstep[0, 1] + "," + Rd_lowstep[0, 2] + "," + Rd_lowstep[0, 3] + "," + Rd_lowstep[0, 4] + "," + Rd_lowstep[0, 5] + ",";
                    AddMsgShow(text_gammaMsg, GammaDebugflag, MecordMsg);
                }
                //已经初始化初始化，必须要更接近目标值才更新下限
                else if ((Rd_lowstep[0, 3] <= now_XYZ[0]) && (Rd_lowstep[0, 4] <= now_XYZ[1]) && (Rd_lowstep[0, 5] <= now_XYZ[2])) //新测试的比之前low记录大
                {
                    if ((Rd_lowstep[0, 0] <= Old_RGB_A[0]) && (Rd_lowstep[0, 1] <= Old_RGB_A[1]) && (Rd_lowstep[0, 2] <= Old_RGB_A[2])) //新测试的比之前记录小
                    {
                        Rd_lowstep[0, 0] = Old_RGB_A[0]; Rd_lowstep[0, 1] = Old_RGB_A[1]; Rd_lowstep[0, 2] = Old_RGB_A[2];
                        Rd_lowstep[0, 3] = now_XYZ[0]; Rd_lowstep[0, 4] = now_XYZ[1]; Rd_lowstep[0, 5] = now_XYZ[2];
                        Rd_lowstep[0, 7] += 1;
                        MecordMsg = "Lowdate =(" + Rd_lowstep[0, 7] + "," + Rd_lowstep[0, 0] + "," + Rd_lowstep[0, 1] + "," + Rd_lowstep[0, 2] + "," + Rd_lowstep[0, 3] + "," + Rd_lowstep[0, 4] + "," + Rd_lowstep[0, 5] + ",";
                        AddMsgShow(text_gammaMsg, GammaDebugflag, MecordMsg);
                    }
                }
            }
            */

            //--------更新记录的上下限限制--------------------
            nowgray = NodePos_A[Nowindex];

            recordMsg = "     //" + nowgray.ToString() + "-" + TuneLoopRecord.ToString() + " Lvxy=(" + now_XYZ[1].ToString("N5") + " ," + now_sx.ToString("N5") + " ," + now_sy.ToString("N5") + ")";
            recordMsg += "  XYZ=(" + now_XYZ[0].ToString("N5") + " ," + now_XYZ[1].ToString("N5") + " ," + now_XYZ[2].ToString("N5") + ")";
            recordMsg += " Now_RGB =(" + Old_RGB_A[0].ToString() + "," + Old_RGB_A[1].ToString() + "," + Old_RGB_A[2].ToString() + ")-";
            // AddMsgShow(text_gammaMsg, GammaDebugflag, recordMsg);

            #endregion
            #region //judge and compared ;
            flag_Lv = 0;
            flag_sx = 0;
            flag_sy = 0;
            // judge 判断是否符合要求，分别判断的目的，是为了减少if 嵌套，提高代码可阅读性；
            if ((now_XYZ[1] < Nodetarget[Nowindex].UpLv) && (now_XYZ[1] > Nodetarget[Nowindex].LowLv)) flag_Lv = 1;
            //亮度符合要求
            if (Math.Abs(now_sy - Nodetarget[Nowindex].sy) < Nodetarget[Nowindex].Limit_sy) flag_sy = 1;
            //sx OK 值1
            if (Math.Abs(now_sx - Nodetarget[Nowindex].sx) < Nodetarget[Nowindex].Limit_sx) flag_sx = 1; //sx OK 值1
            ///判断是否符合，如果符合则下一绑点index
            if ((flag_Lv == 1) && (flag_sy == 1) && (flag_sx == 1))// 当前灰阶符合要求，将nowindex 下移，并清零记录次数
            {
                recordMsg = "     Finished gray-" + NodePos_A[Nowindex] + "  Target_Lv=" + Target_XYZ[1, Nowindex].ToString("N5") + "  Measur_Lv=" + now_XYZ[1].ToString("N5") + " sx=" + now_sx.ToString("N5") + " sy=" + now_sy.ToString("N5") + "  OK!\r\n";
                AddMsgShow(text_gammaMsg, GammaDebugflag, recordMsg);
                Nowindex--;
                TuneLoopRecord = -1;

            }
            //判断调试次数是否超限制，如果超限制则切到下一绑点index
            if (GrayTune_loopnum[Nowindex] < TuneLoopRecord) //次数超限制
            {
                recordMsg = "// Over 次数 gray-" + NodePos_A[Nowindex] + "  手动确认!\r\n";
                Nowindex--; //强制切下一灰阶点；  
                TuneLoopRecord = -1;
                recordMsg += "// 强制切tune   Nowgray=" + nowgray.ToString() + Target_XYZ[1, Nowindex] + "\r\n";
                AddMsgShow(text_gammaMsg, GammaDebugflag, recordMsg);

            }
            //判断是否从上一绑点切换过来的且不是0灰阶
            if ((TuneLoopRecord == -1) && (Nowindex > 0)) //新切过来的灰阶，且当前不是0灰阶，继续调试
            {
                nowgray = NodePos_A[Nowindex]; //获取当前index 对应灰阶

                if ((RGB_RefValue_A[1][Nowindex] == 0) | (RGB_RefValue_A[0][Nowindex + 1] == 0) | (RGB_RefValue_A[1][Nowindex + 1] == 0) | (RGB_RefValue_A[2][Nowindex + 1] == 0))
                {
                    TuneLoopRecord = 1; // 估算值直接调试
                    RGB_Value_A[0][Nowindex] = RGB_Value_A[0][Nowindex + 1]; //获取当前将上一次绑点值赋值到此绑点
                    RGB_Value_A[1][Nowindex] = RGB_Value_A[1][Nowindex + 1];
                    RGB_Value_A[2][Nowindex] = RGB_Value_A[2][Nowindex + 1];
                }
                else
                {
                    TuneLoopRecord = 0; //参考值 先跳过调试，测试完再算  ICGT.NodeEffetNum - 1
                    RGB_Value_A[0][Nowindex] = (Int16)(RGB_RefValue_A[0][Nowindex] * RGB_Value_A[0][Nowindex + 1] / RGB_RefValue_A[0][Nowindex + 1]); //获取当前将上一次绑点值赋值到此绑点
                    RGB_Value_A[1][Nowindex] = (Int16)(RGB_RefValue_A[1][Nowindex] * RGB_Value_A[1][Nowindex + 1] / RGB_RefValue_A[1][Nowindex + 1]);
                    RGB_Value_A[2][Nowindex] = (Int16)(RGB_RefValue_A[2][Nowindex] * RGB_Value_A[2][Nowindex + 1] / RGB_RefValue_A[2][Nowindex + 1]);
                }
                recordMsg = "// start tune gray=" + nowgray.ToString() + " ";
                recordMsg += "    Target_XYZ=(" + Target_XYZ[0, Nowindex].ToString("N5") + "," + Target_XYZ[1, Nowindex].ToString("N5") + "," + Target_XYZ[2, Nowindex].ToString("N5") + ")" + "    Now_RGB = "; ;

                AddMsgShow(text_SendMsg, SendDebugflag, recordMsg);
                try
                {
                    WriteComport("99 90 00 00"); //切回高速
                    Thread.Sleep(10);
                    //Pattern_Write(nowgray, nowgray, nowgray); //切patteren
                    Pattern_Write(nowgray, nowgray, nowgray, Picpath);// 灰阶测试
                    Thread.Sleep(10);
                    Thread.Sleep(ChangePicDelay);
                }
                catch (Exception emsg)//错误处理
                {
                    MessageBox.Show(emsg.Message, "Error Message");
                    Stopflag = true;
                    T2_autogamma.Enabled = false;//开始计时器
                    return;
                }

            }
            if (Nowindex == 0) //新切过来的灰阶，且当前是0灰阶，则此段gamma调试完成
            {
                T2_autogamma.Enabled = false;//停止计时器
                recordMsg = "Finished this mode gray tune !\r\n";
                AddMsgShow(text_gammaMsg, GammaDebugflag, recordMsg);
                SavetextFile(Gammacodepath, text_script_send_all.Text, true);
                SavetextFile(Gammacodepath + ".log", text_gammaMsg.Text, true); Stopflag = true;
                //string inipath
                SaveGammacodeRecord(ICGT.GGN_SelectSectionlist[ICGT.GGSectionTuneNum].Replace("$", ""), Gamma_RGBValueRecordIni);

                ICGT.GGSectionTuneNum += 1;
                if (ICGT.GGSectionTuneNum < ICGT.GGN_SelectSectionlist.Length - 1)
                {
                    Gamma_TuneSection_Load(ICGT.GGSectionTuneNum);

                    flag_Lv = 0; flag_sx = 0; flag_sy = 0;
                    T2_autogamma.Enabled = true;//开始计时器
                }
                else
                {
                    if (ICGT.ExitGammaMode_Code != "") getcode = Write99Comport_Script(ICGT.ExitGammaMode_Code);
                    recordMsg = "//========Finished All mode gray tune !========\r\n";
                    AddMsgShow(text_gammaMsg, GammaDebugflag, recordMsg);
                }
                return;// 跳出，不执行下边code
            }

            // 以上已完成判断，进行调试 
            // 执行此部分原因为：1.当前灰阶不符合spec；2.当前灰阶已符合，但下一需要调试灰阶不是0，需要继续调下一灰阶；

            double test_orgindex = 0, test_newindex = 0, test_targetXYZ = 0, test_MeasurXYZ = 0, test_diff = 0;
            string recordstring = "";
            double step2lum;
            double Recordstep_RGB = 0;
            //目标亮度是否是0.5nit
            if ((TuneLoopRecord > 0) && (Target_XYZ[1, Nowindex] >= 0.5))
            {
                int sign = 1;
                for (int i = 0; i < 3; i++)
                {
                    diffXYZ[i] = (now_XYZ[i] - Target_XYZ[i, Nowindex]) / (now_XYZ[i] + Target_XYZ[i, Nowindex]);
                    test_orgindex = RGB_Value_A[i][Nowindex];
                    test_targetXYZ = Target_XYZ[i, Nowindex];
                    test_MeasurXYZ = now_XYZ[i];
                    test_diff = diffXYZ[i];
                    if (test_diff > 0) { sign = -1; } //偏大则 减小
                    if (test_diff <= 0) { sign = 1; } // 偏小则 增大
                    recordstring += i.ToString() + "  point:";
                    //if ((record_oldRGBstep[i] == 0 || record_oldXYZ[i] < 0.5)) //没有估算记录
                    if ((record_oldRGBstep[i] == 0 || record_oldXYZ[i] == 0)) //没有估算记录
                    {
                        //test_diff = Math.Abs(test_diff);
                        recordstring += " no record,";
                        if (Math.Abs(test_diff) >= 0.02)
                        {
                            recordstring += " test_diff>0.02 , ";
                            Recordstep_RGB = (Int16)(1000 * Math.Abs(test_diff) * sign);
                            test_newindex = test_orgindex + Recordstep_RGB;
                            RGB_Value_A[i][Nowindex] = (Int16)test_newindex;
                        }
                        else if ((Math.Abs(test_diff) > 0.01) && (nowgray > 64))
                        {
                            recordstring += " test_diff>0.01 , ";
                            Recordstep_RGB = (Int16)(5 * sign);
                            //test = RGB_Value_A[i][Nowindex] * (1 - diffXYZ[i] * 0.9);
                        }
                        else
                        {
                            Recordstep_RGB = (Int16)(1 * sign);
                        }
                        test_newindex = test_orgindex + Recordstep_RGB;
                        RGB_Value_A[i][Nowindex] = (Int16)test_newindex;
                        recordstring += "diff=" + test_diff.ToString("N3") + " , " + i.ToString() + "-step=" + Recordstep_RGB.ToString("N3") + "  ";

                    }
                    else
                    {
                        //高阶快速算法 根据记录上一步的 步长和亮度变化，推算step

                        recordstring += " HGF , ";
                        step2lum = (now_XYZ[i] - record_oldXYZ[i]) / record_oldRGBstep[i];
                        Recordstep_RGB = (Int16)((-now_XYZ[i] + Target_XYZ[i, Nowindex]) / step2lum);
                        if ((Recordstep_RGB * sign) < 0)
                            Recordstep_RGB = (Int16)(30 * Math.Abs(test_diff) * sign); //排除受其他RGB影响,干扰符号不对
                        test_newindex = test_orgindex + Recordstep_RGB;
                        RGB_Value_A[i][Nowindex] = (Int16)test_newindex;
                        recordstring += i.ToString() + " diff=" + test_diff.ToString("N3") + " , " + i.ToString() + "-step=" + Recordstep_RGB.ToString("N3") + "  ";

                    }
                }

            }
            //elseif 低灰阶 调试策略，

            else if ((TuneLoopRecord > 0) && (Target_XYZ[1, Nowindex] < 0.5))// 亮度低于0.1nit 只要求Y亮度，不管x,y 
            {
                Int16 sign = 1;
                double[] diff_XYZ = new double[4];
                double Max_diff;
                int recode_rgb;
                diff_XYZ[0] = (now_XYZ[0] - Target_XYZ[0, Nowindex]) / (Target_XYZ[0, Nowindex] + now_XYZ[0]);
                diff_XYZ[1] = (now_XYZ[1] - Target_XYZ[1, Nowindex]) / (Target_XYZ[1, Nowindex] + now_XYZ[1]);
                diff_XYZ[2] = (now_XYZ[2] - Target_XYZ[2, Nowindex]) / (Target_XYZ[2, Nowindex] + now_XYZ[2]);
                recode_rgb = 1; Max_diff = Math.Abs(diff_XYZ[1]); //1 设定操作index 为Y

                Max_diff = Math.Abs(diff_XYZ[0]); recode_rgb = 0;

                if (Max_diff < Math.Abs(diff_XYZ[2]))
                {
                    recode_rgb = 2; Max_diff = Math.Abs(diff_XYZ[2]); //最大值竞争
                }
                if (Max_diff < Math.Abs(diff_XYZ[1])) //绿色优先
                {
                    recode_rgb = 1; Max_diff = Math.Abs(diff_XYZ[1]);
                }

                test_diff = diff_XYZ[recode_rgb];
                if (test_diff > 0) { sign = -1; } //偏大则 减小
                if (test_diff <= 0) { sign = 1; } // 偏小则 增大
                if (record_oldRGBstep[recode_rgb] == 0) //上步无记录则估值
                {
                    recordstring += " ULDCM , ";
                    Recordstep_RGB = (0.5 * diff_XYZ[recode_rgb] * RGB_Value_A[recode_rgb][Nowindex + 1]);
                }
                else //上步有记录则根据上一步估值
                {
                    recordstring += " ULDRD , ";
                    step2lum = (now_XYZ[recode_rgb] - record_oldXYZ[recode_rgb]) / record_oldRGBstep[recode_rgb];
                    Recordstep_RGB = (Int16)((-now_XYZ[recode_rgb] + Target_XYZ[recode_rgb, Nowindex]) / step2lum);
                    //test_newindex = test_orgindex + Recordstep_RGB;
                }
                //防止落入震荡
                if (Math.Abs(Recordstep_RGB) > 20 && Math.Abs(Recordstep_RGB + record_oldRGBstep[recode_rgb]) < 10) Recordstep_RGB = Recordstep_RGB * 0.5;
                //防止step 太小
                if (Recordstep_RGB < 0 && Recordstep_RGB > -2) Recordstep_RGB = -2;
                if (Recordstep_RGB > 0 && Recordstep_RGB < 2) Recordstep_RGB = 2;
                if ((Recordstep_RGB * sign) < 0)
                    Recordstep_RGB = (Int16)(RGB_Value_A[1][Nowindex + 1] / 4 * Math.Abs(test_diff) * sign); //排除加减符号不对，则使用差值估值
                RGB_Value_A[0][Nowindex] += (Int16)(Recordstep_RGB * diff_XYZ[0] / diff_XYZ[recode_rgb]);
                RGB_Value_A[1][Nowindex] += (Int16)(Recordstep_RGB * diff_XYZ[1] / diff_XYZ[recode_rgb]);
                RGB_Value_A[2][Nowindex] += (Int16)(Recordstep_RGB * diff_XYZ[2] / diff_XYZ[recode_rgb]);
                recordstring += "rgb =  " + recode_rgb.ToString() + " Recordstep_RGB=" + Recordstep_RGB.ToString("N3") + "  ";

            }

            /*
              if ((Rd_lowstep[0, 7] > 0) && (Rd_upstep[0, 7] > 0)) // 动态上下限限制已更新，具有参考意义
              {
                  for (int i = 0; i < 3; i++)  //判断 数值是否超规，是否在上限限制以内,如果不在合理范围内，使用上限方法进行修正
                  {
                      if ((RGB_Value_A[i][Nowindex] < Rd_lowstep[0, i]) || (RGB_Value_A[i][Nowindex] > Rd_upstep[0, i]))
                      {
                          MecordMsg = "limint do =(" + i.ToString() + "," + Rd_lowstep[0, i] + "," + RGB_Value_A[i][Nowindex] + "," + Rd_upstep[0, i];
                          AddMsgShow(text_gammaMsg, GammaDebugflag, MecordMsg);
                          RGB_Value_A[i][Nowindex] = (Int16)(Rd_lowstep[0, i] + ((Rd_upstep[0, i] - Rd_lowstep[0, i]) * (now_XYZ[0] - Rd_lowstep[0, 3 + i]) / (Rd_upstep[0, 3 + i] - Rd_lowstep[0, 3 + i])));
                      }
                  }
              }
              */
            // ======整体判断 灰阶数值是否合理=====
            for (int i = 0; i < 3; i++)  //判断 数值是否超规，不能大于最大，或上一绑点，也不能小于0
            {
                recordMsg += RGB_Value_A[i][Nowindex] + ",";
                if ((RGB_Value_A[i][Nowindex] <= 0))
                {
                    record_oldRGBstep[i] = (Int16)(-RGB_Value_A[i][Nowindex]);
                    RGB_Value_A[i][Nowindex] = 1;

                }
                else if ((nowgray == 255) && (RGB_Value_A[i][Nowindex] > MaxNodeValue_A[Nowindex]))
                {
                    //record_oldRGBstep[i] = (Int16)(MaxNodeValue_A[Nowindex] - RGB_Value_A[i][Nowindex]);
                    RGB_Value_A[i][Nowindex] = MaxNodeValue_A[Nowindex];
                }
                else if ((nowgray < 255) && (RGB_Value_A[i][Nowindex] > RGB_Value_A[i][Nowindex + 1]))
                {
                    //record_oldRGBstep[i] = (Int16)(RGB_Value_A[i][Nowindex + 1] - RGB_Value_A[i][Nowindex]);
                    RGB_Value_A[i][Nowindex] = RGB_Value_A[i][Nowindex + 1];
                }


                record_oldXYZ[i] = now_XYZ[i];
                record_oldRGBstep[i] = (Int16)(RGB_Value_A[i][Nowindex] - Old_RGB_A[i]);
            }
            //  recordMsg = "       //" + nowgray.ToString() + "Next_RGB=(" + RGB_Value_A[0][Nowindex] + "," + RGB_Value_A[1][Nowindex] + "," + RGB_Value_A[2][Nowindex] + ")" + "  Target_Lv=" + Target_XYZ[1, Nowindex].ToString("N5") + recordstring + "\r\n"; ;
            if (GammaFullDebugflag == true) recordMsg += recordstring;// 详细debug mode 开启
            AddMsgShow(text_gammaMsg, GammaDebugflag, recordMsg);

            try
            {
                NodevalueZoom(0, Nowindex);
                Nodevalue2ParValue(0, 0, 0);
                //getcode = GetWitercode(0, Nowindex);
                getcode = GetWitercode(0, 0);
                AddScriptShow(text_script_send_all, ScriptDebugflag, getcode);
                Write6AComport_Script(getcode, HF_GenW_port);
            }
            catch (Exception emsg)
            {
                MessageBox.Show(emsg.Message, "Error Message");
                Stopflag = true;
                T2_autogamma.Enabled = false;//开始计时器
                return;
            }

            if (Stopflag == true)
            {
                T2_autogamma.Enabled = false;//停止计时器
                return;
            }
            else
            {
                flag_Lv = 0; flag_sx = 0; flag_sy = 0;
                T2_autogamma.Enabled = true;//开始计时器
            }


            #endregion
        }

        string Gammacodepath = "Autogammacode.txt";
        private void Btn_measure3_Click(object sender, EventArgs e)
        {
            //CASDataType Grminlevel, Grymaxlevel;
            string temselect_sectionlist = "", ss;
            int delay_time;
            delay_time = Convert.ToInt16(text_TuneDelayTime.Text);
            ChangePicDelay = Convert.ToInt16(text_delaytime.Text);
            Stopflag = false;
            foreach (TreeNode tn in treeView_GammaGroupN.Nodes)
            {
                temselect_sectionlist += "$";
                foreach (TreeNode subtn in tn.Nodes)
                {
                    if (subtn.Checked == true) temselect_sectionlist += subtn.Tag + ";";
                }
            }
            ICGT.GGN_SelectSectionlist = temselect_sectionlist.Split(';');
            if ((ICGT.GGN_SelectSectionlist.Length <= 1) || (temselect_sectionlist == ""))
            {
                MessageBox.Show("没有选择任何一组需要调试gamma ,请先选择要调试gamma 再开始！");
            }
            else
            {
                if ((checkBox_Pattern_Pic.Checked == true) | (ICGT.GGN_Picname != "")) //AOD 图片 mode
                {
                    Picpath = textBox2.Text + "\\" + ICGT.GGN_Picname;
                }
                else
                {
                    Picpath = "";
                }
                Gammacodepath = Application.StartupPath + "\\HF_Autogamma\\" + DateTime.Now.ToString("yyyy-MM-dd");
                if (!Directory.Exists(Gammacodepath))
                {
                    Directory.CreateDirectory(Gammacodepath);
                }
                Gammacodepath = Application.StartupPath + "\\HF_Autogamma\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + text_AutoPanelNo.Text + "_" + DateTime.Now.ToString("_Hmmss") + ".txt";

                //  Gammacodepath = Gammacodepath.PadLeft 
                //  ICGT.GGN_SelectSectionlist.Length -= 1;
                try
                {
                    WriteComport("99 90 00 00"); //切回高速
                    //Pattern_Write(0, 0, 0);// 灰阶测试
                    Pattern_Write(0, 0, 0, Picpath);// 灰阶测试
                    Thread.Sleep(1500);
                    CaSDKObj.CASDK_AutoMeasure();
                    // btnCal_manual_Click(sender, e);// 自动连接校准

                    if (ICGT.EnterGammaMode_Code != "") ss = Write99Comport_Script(ICGT.EnterGammaMode_Code);
                }
                catch (Exception emsg)
                {
                    MessageBox.Show(emsg.Message, "Error Message");
                    Stopflag = true;
                    return;
                }
                text_gammaMsg.Visible = true;
                //  text_scriptSend.Height = 150;
                treeView_GammaGroupN.Height = 260;
                GGourpBox.Height = 442;
                GrMindata.SetLvxy(CaSDKObj.Lv, CaSDKObj.sx, CaSDKObj.sy);//获取最小值
                GrMindata.R_index = GrMindata.G_index = GrMindata.B_index = 0;
                ICGT.GGSectionTuneNum = 0;//全局变量，记录当前调试gamma Section 位于待调列表的位置
                TuneLoopRecord = 0;
                text_gammaMsg.Text = "";
                text_RecMsg.Text = "";

                Gamma_TuneSection_Load(ICGT.GGSectionTuneNum);//调用GGN_SelectSectionlist 里面的GGSectionTuneNum index 下的group

                Rd_lowstep[0, 7] = 0; Rd_upstep[0, 7] = 0; //重新更新上下限限制

                Thread.Sleep(500);
                Stopflag = false;
                T2_autogamma.Enabled = false;
                T2_autogamma.Interval = delay_time;
                T2_autogamma.Enabled = true;
            }


            //设定目标值 

        }

        private void Gamma_TuneSection_Load(int selectindex)
        {
            //具体需要调试group 存放于 GGN_SelectSectionlist，根据指定的selectindex ，load target and limit 信息，然后自动调试
            int delay_time;
            double setgammarate;
            string tempread;
            // inital 调试gamma 亮度等信息

            tempread = ICGT.GGN_SelectSectionlist[selectindex].Replace("$", "");
            if (ICGT.GGN_SelectSectionlist[selectindex].Substring(0, 1) == "$")
            {
                GetgammCfg(0, tempread);
            }
            GetgammCfg(1, tempread);

            //ShowArray();
            AddScriptShow(text_script_send_all, ScriptDebugflag, ICGT.GGN_ClickCode);
            SavetextFile(Gammacodepath, text_script_send_all.Text, true);
            //更新 调试目标值部分
            Picpath = "";
            if ((ICGT.GGN_Picname != "")) //AOD 图片 mode
            {
                Picpath = textBox2.Text + "\\" + ICGT.GGN_Picname;
            }

            if ((ICGT.GGN_FrameRate != "") & (ICGT.GGN_FrameRate != CA410_Measure_Freq.Text)) //频率
            {
                CA410_Measure_Freq.Text = ICGT.GGN_FrameRate;
                CaSDKObj.SingleCalibration(0, byte.Parse(CA310_Channel.Text), double.Parse(CA410_Measure_Freq.Text));
            }
            if (ICGT.GGN_Target != "") //不等空，获取新的target 
            {
                string[] subtarget = ICGT.GGN_Target.Split(';');
                string[] subsubtarget = subtarget[0].Split(',');
                if (subsubtarget[0] == "*")
                {
                    text_gamaRate.Tag = "*";
                    // subsubtarget = subtarget[1].Split(',');
                    text_gamaRate.Text = subsubtarget[1];
                    text_255targe_lv.Text = subsubtarget[2];
                    text_255targe_sx.Text = subsubtarget[3];
                    text_255targe_sy.Text = subsubtarget[4];
                    // Delayms(100);
                    setgammarate = Convert.ToDouble(subsubtarget[1]);

                    GrMaxTarget.SetLvxy(Convert.ToDouble(subsubtarget[2]), Convert.ToDouble(subsubtarget[3]), Convert.ToDouble(subsubtarget[4]));
                    GrMaxTarget.R_index = GrMaxTarget.G_index = GrMaxTarget.B_index = 255;
                    // 刷新计算对应band 的 gamma target and limit
                    Cacla_Target(setgammarate, GrMindata, GrMaxTarget, ICGT.MaxLooptune);
                }
            }
            else
            {
                setgammarate = Convert.ToDouble(text_gamaRate.Text);
                GrMaxTarget.SetLvxy(Convert.ToDouble(text_255targe_lv.Text), Convert.ToDouble(text_255targe_sx.Text), Convert.ToDouble(text_255targe_sy.Text));
                GrMaxTarget.R_index = GrMaxTarget.G_index = GrMaxTarget.B_index = 255;
                // 刷新计算对应band 的 gamma target and limit
                Cacla_Target(setgammarate, GrMindata, GrMaxTarget, ICGT.MaxLooptune);
            }
            try
            {
                Stopflag = false;
                IClosing = true; //关闭自动recivew
                SerialPort_ReadOpen();
                string ss = Write99Comport_Script(text_script_send_all.Text);
                SerialPort_ReadClose();
            }
            catch (Exception emsg)
            {
                if (MessageBox.Show(Err_report + "\r\n" + emsg.Message + "\r\n continue run?", "Error Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    Stopflag = true;
                    return;
                }
            }

            delay_time = Convert.ToInt16(text_TuneDelayTime.Text);
            Nowindex = ICGT.NodeEffetNum - 1;
            //切换pattern
            WriteComport("99 90 00 00"); //切回高速
            Thread.Sleep(10);
            nowgray = NodePos_A[Nowindex];
            Pattern_Write(nowgray, nowgray, nowgray, Picpath);
            Thread.Sleep(1500);
            record_oldXYZ[0] = 0; record_oldXYZ[1] = 0; record_oldXYZ[2] = 0; //初始化估算值
            record_oldRGBstep[0] = 0; record_oldRGBstep[1] = 0; record_oldRGBstep[2] = 0; //初始化估算值     
            TuneLoopRecord = 0;

            Rd_lowstep[0, 7] = 0; Rd_upstep[0, 7] = 0; //重新更新上下限限制
            text_gammaMsg.Text = "// Star tune Nowgray=" + nowgray.ToString() + "\r\n";
            text_RecMsg.Text += "// Star tune Nowgray=" + nowgray.ToString() + "\r\n";
            //Nodevalue2ParValue(0x42, Nowindex, Nowindex); //2=从UI ref获取值并,RGB_value只获取255 值
            //  LoadGammacodeRecord(ICGT.GGN_SelectSectionlist[ICGT.GGSectionTuneNum], Gamma_RGBValueRecordIni);//  调取之前存储的record 数值

            LoadGammacodeRecord(ICGT.GGN_SelectSectionlist[ICGT.GGSectionTuneNum].Replace("$", ""), Gamma_RGBValueRecordIni);//  调取之前存储的record 数值
            Nodevalue2ParValue(0x10, Nowindex, Nowindex); //2=从UI ref获取值并,RGB_value只获取255 值
            NodevalueZoom(0, Nowindex); //其余灰阶值等比255

            string getcode = GetWitercode(0, 0);
            AddScriptShow(text_script_send_all, ScriptDebugflag, getcode);
            Write6AComport_Script(getcode, HF_GenW_port);
            TuneLoopRecord = 0;
        }


        //=================================================================
        private void SaveGammacodeRecord(string GammaTuneNode, String iniPath)
        {
            bool result;
            string temRGB = "";

            for (int j = 0; j < NodePos_A.Length; j++)
            {
                // k = ICGT.NodeFollow_A[j];//NodeFollow_A 内 存储着 index 重新maping 关系，在cfg 时生成
                temRGB += NodePos_A[j].ToString() + ",";
            }
            result = WritePrivateProfileString(GammaTuneNode, "Node_position", temRGB, iniPath);
            for (int i = 0; i < 3; i++)
            {
                temRGB = "";
                for (int j = 0; j < ICGT.NodeNum; j++)
                {
                    // k = ICGT.NodeFollow_A[j];//NodeFollow_A 内 存储着 index 重新maping 关系，在cfg 时生成
                    temRGB += RGB_Value_A[i][j].ToString() + ",";
                }
                if (i == 0) { result = WritePrivateProfileString(GammaTuneNode, "R_recordValue", temRGB, iniPath); }
                if (i == 1) { result = WritePrivateProfileString(GammaTuneNode, "G_recordValue", temRGB, iniPath); }
                if (i == 2) { result = WritePrivateProfileString(GammaTuneNode, "B_recordValue", temRGB, iniPath); }
            }
        }
        private void LoadGammacodeRecord(string GammaTuneNode, String iniPath)
        {
            string temRGBlist;
            string[] RGBarray;
            int temlength;
            temRGBlist = ReadIni(GammaTuneNode, "R_recordValue", iniPath);
            if (temRGBlist != "")
            {
                RGBarray = temRGBlist.Split(',');
                temlength = ICGT.NodeNum;
                if (RGBarray.Length <= ICGT.NodeNum) temlength = RGBarray.Length - 1;
                for (int j = 0; j < temlength; j++)
                {
                    RGB_RefValue_A[0][j] = Convert.ToInt16(RGBarray[j]);
                }
            }
            temRGBlist = ReadIni(GammaTuneNode, "G_recordValue", iniPath);
            if (temRGBlist != "")
            {
                RGBarray = temRGBlist.Split(',');
                temlength = ICGT.NodeNum;
                if (RGBarray.Length <= ICGT.NodeNum) temlength = RGBarray.Length - 1;
                for (int j = 0; j < temlength; j++)
                {
                    RGB_RefValue_A[1][j] = Convert.ToInt16(RGBarray[j]);
                }
            }
            temRGBlist = ReadIni(GammaTuneNode, "B_recordValue", iniPath);
            if (temRGBlist != "")
            {
                RGBarray = temRGBlist.Split(',');
                temlength = ICGT.NodeNum;
                if (RGBarray.Length <= ICGT.NodeNum) temlength = RGBarray.Length - 1;
                for (int j = 0; j < temlength; j++)
                {
                    RGB_RefValue_A[2][j] = Convert.ToInt16(RGBarray[j]);
                }

            }
        }
        #endregion/Auto gamma end 

        #region //Ryduim GIR auto tune
        private void Ryduim_GIR(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            int delaytime;
            int Rrate = 0, Grate = 0, Brate = 0;
            int Scandirection = 1, startindex = 0;
            int[] Measure_level = new int[256];
            int MeasureNum = 255;

            if ((checkBox_Pattern_Pic.Checked == true) | (ICGT.GGN_Picname != "")) //AOD 图片 mode
            {
                Picpath = textBox2.Text + "\\" + ICGT.GGN_Picname;
            }
            else
            {
                Picpath = "";
            }

            try
            {
                // 量测255亮度与0灰阶亮度，为归一化做准备
                nowgray = 255;
                Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate, Picpath);// 灰阶测试
                //Pattern_Write(ICGT.ICName ,nowgray* Rrate, nowgray* Grate, nowgray* Brate, true);
                Thread.Sleep(2000);
                CaSDKObj.CASDK_AutoMeasure();
                Grmaxlum = CaSDKObj.Lv;

            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }


            for (int i = 0; i < MeasureNum; i++)
            {
                if (Stopflag == true) { break; }

                delaytime = Convert.ToInt32(text_delaytime.Text);
                nowgray = Measure_level[startindex + i * Scandirection];
                measure_Num = measure_Num + 1;
                numPattern_W.Text = nowgray.ToString();
                try
                {
                    //Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate);

                    Pattern_Write(nowgray * Rrate, nowgray * Grate, nowgray * Brate, Picpath);// 灰阶测试
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }

                // Pattern_Write(ICGT.ICName, temlevel * Rrate, temlevel * Grate, temlevel * Brate, false);
                Thread.Sleep(delaytime);

                CaSDKObj.CASDK_AutoMeasure();
                nowlum = CaSDKObj.Lv;
                GC_Lv[measure_Num] = (nowlum - Grminlum) / (Grmaxlum - Grminlum);
                GC_gray[measure_Num] = nowgray;
                CAS200_AddData(nowgray.ToString(), nowlum, CaSDKObj.sx, CaSDKObj.sy, CaSDKObj.T, CaSDKObj.duv, CaSDKObj.X, CaSDKObj.Y, CaSDKObj.Z);
                GC_gray[0] = i + 1;
                // i = i + 4;  
                Delay(1);
                Update_Paint();


            }



        }


        #endregion/Ryduim GIR auto tune end



        #region //testpart

        private void button1_Click(object sender, EventArgs e)
        {

            WriteComport(text_SendMsg.Text);
            T1.Enabled = false;
            T1.Interval = 2000;
            T1.Enabled = true;
            //Thread.Sleep(200);
            //RM692AX_Reg_Addr.Text= Readbuff+ "$44444 /r/n" ;

        }

        private void button2_Click(object sender, EventArgs e)
        {

            string get6Acode = TransCode(text_script_send_all.Text, HF_GenW_port);

            WriteComport(get6Acode);
            int num;
            get6Acode = SerialPort_Read(100 * 15, out num, out readbuff);
            //Application.DoEvents;
            //T1.Enabled = false;
            // T1.Interval = 500;
            // T1.Enabled = true;
        }

        private void listBox_SendScript_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            button4_Click(sender, e);
        }
        //srcitpt 99 run btn
        private void button4_Click(object sender, EventArgs e)
        {
            string Userpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\2K_CFG";
            string fname = Userpath + "\\2K_CFG.inf";
            string sendstr = "";
            int temindex = Convert.ToInt32(text_script_send_all.Tag);

            if (tab_Debug_File.SelectedIndex == 1)// file salect
            {
                sendstr = txt_send_cmd_all.Text;
            }
            else
            {
                if (listBox_SendScript.Items[temindex].ToString() == (temindex + 1).ToString() + "-")
                {
                    listBox_SendScript.Items[temindex] = (temindex + 1).ToString() + "-" + text_script_send_all.Text;
                }
                bool result = WritePrivateProfileString("Lastlog", "DefualtScript" + text_script_send_all.Tag, listBox_SendScript.Items[temindex].ToString(), fname);
                fname = Userpath + "\\DefualtScript\\Script-" + text_script_send_all.Tag;
                StreamWriter sw = null; //文件流 下发code之前自动保存脚本文件
                sw = new StreamWriter(@fname + "_code.txt", false, Encoding.UTF8);
                sw.Write(text_script_send_all.Text); //文本记录功能 ，将当前文本自动固定路径
                sw.Dispose(); //释放资源
                sw.Close(); //关闭数据流   
                sendstr = text_script_send_all.Text;

                ScriptSavestring[temindex] = text_script_send_all.Text;
            }
            try
            {
                Rd_lowstep[0, 7] = 0; Rd_upstep[0, 7] = 0; //重新更新上下限限制
                Stopflag = false;
                IClosing = true; //关闭自动recivew
                SerialPort_ReadOpen();
                //string ss = Write99Comport_muilt(text_scriptSend.Text);
                string ss = Write99Comport_Script(sendstr);
                //text_SendMsg.Text += ss;
            }
            catch (Exception emsg)
            {
                SerialPort_ReadClose();
                if (MessageBox.Show(Err_report + "\r\n" + emsg.Message + "\r\n continue run?", "Error Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    Stopflag = true;
                    return;
                }
                // MessageBox.Show(emsg.Message, "系统提示：");
            }

            SerialPort_ReadClose();

            switch (text_script_send_all.Tag)
            {
                case "0":
                    textBox_Scrinp1.Text = text_script_send_all.Text;
                    this.btn_ScrinpSend1.BackColor = HisClickColor;
                    break;
                case "1":
                    textBox_Scrinp2.Text = text_script_send_all.Text;
                    this.btn_ScrinpSend2.BackColor = HisClickColor;
                    break;
                case "2":
                    textBox_Scrinp3.Text = text_script_send_all.Text;
                    this.btn_ScrinpSend3.BackColor = HisClickColor;
                    break;
                case "3":
                    textBox_Scrinp4.Text = text_script_send_all.Text;
                    this.btn_ScrinpSend4.BackColor = HisClickColor;
                    break;
                case "4":
                    textBox_Scrinp5.Text = text_script_send_all.Text;
                    this.btn_ScrinpSend5.BackColor = HisClickColor;
                    break;
                case "5":
                    textBox_Scrinp6.Text = text_script_send_all.Text;
                    this.btn_ScrinpSend6.BackColor = HisClickColor;
                    break;
                case "6":
                    textBox_Scrinp7.Text = text_script_send_all.Text;
                    this.btn_ScrinpSend7.BackColor = HisClickColor;
                    break;
                case "7":
                    textBox_Scrinp8.Text = text_script_send_all.Text;
                    this.btn_ScrinpSend8.BackColor = HisClickColor;
                    break;
                default:
                    break;
            }

        }

        private void RM692AX_Others_Click(object sender, EventArgs e)
        {
            Send_buf = new byte[74];
            Button btnTmp = (Button)sender;
            Setting.TempRecord.cmdLen = 7;

            Send_buf[0] = 0x3E;        //RM692AX
            Send_buf[2] = 0x02;
            switch (btnTmp.Name)
            {
                case "RM692AX_Reg_R":       //              2
                    {
                        //Send_buf[1] = 0x02;
                        //Send_buf[3] = byte.Parse((Convert.ToInt32(RM692AX_Reg_Addr.Text.Trim(), 16)).ToString());
                        //Send_buf = new byte[74];
                        Setting.TempRecord.cmdLen = 74;
                        Send_buf[2] = 69;
                        Send_buf[3] = 0;
                        Send_buf[0] = 0x3F; //RM692CX

                        Send_buf[1] = 0x05;                             //读 Red Gamma
                        Send_buf[3] |= 0x00;
                        Send_buf[4] = 0x01;
                    }
                    break;
                case "RM692AX_Reg_W":         //w写寄存器   1
                    {
                        Send_buf[1] = 0x01;
                        Send_buf[3] = byte.Parse((Convert.ToInt32(RM692AX_Reg_Addr.Text.Trim(), 16)).ToString());
                        Send_buf[4] = byte.Parse((Convert.ToInt32(RM692AX_Reg_Data.Text.Trim(), 16)).ToString());
                    }
                    break;

            }
            //int bufm = Send_buf.Length - 2;
            CRCData.CalculateCrc16(Send_buf, out Send_buf[Send_buf.Length - 2], out Send_buf[Send_buf.Length - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 74);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            T1.Enabled = false;
            T1.Interval = 2000;
            T1.Enabled = true;
        }
        #endregion
    }
}
